admin管理员组

文章数量:1297094

Given Problem: Write a function called "sumDigits".

Given a number, "sumDigits" returns the sum of all its digits.

var output = sumDigits(1148);
console.log(output); // --> 14

If the number is negative, the first digit should count as negative.

var output = sumDigits(-316);
console.log(output); // --> 4

My code:

function sumDigits(num) {
  return num.toString().split("").reduce(function(a, b){
    return parseInt(a) + parseInt(b);
  });
}

My code solves the problem for positive integers. Any hints on how should I go about solving the problem for negative integers? Please and thanks.

Edit: And what if the given number is 0? Is it acceptable to add an if statement to return 0 in such cases?

Given Problem: Write a function called "sumDigits".

Given a number, "sumDigits" returns the sum of all its digits.

var output = sumDigits(1148);
console.log(output); // --> 14

If the number is negative, the first digit should count as negative.

var output = sumDigits(-316);
console.log(output); // --> 4

My code:

function sumDigits(num) {
  return num.toString().split("").reduce(function(a, b){
    return parseInt(a) + parseInt(b);
  });
}

My code solves the problem for positive integers. Any hints on how should I go about solving the problem for negative integers? Please and thanks.

Edit: And what if the given number is 0? Is it acceptable to add an if statement to return 0 in such cases?

Share edited May 3, 2017 at 21:34 Vikrant Singh asked May 3, 2017 at 21:14 Vikrant SinghVikrant Singh 821 gold badge2 silver badges12 bronze badges 4
  • 1 @RolandIllig The question says that if the number is negative the first digit is considered negative – Andrew Li Commented May 3, 2017 at 21:17
  • 4 And, by the way, this question looks like please do my homework. This site is not a free homework service. – Roland Illig Commented May 3, 2017 at 21:17
  • @RolandIllig He is not asking us to do his homework. He is asking help on a specific part of the work he already started. Whether this is homework or not, it is a perfectly fine question on Stack Overflow. – blex Commented May 3, 2017 at 21:21
  • 2 How is this 'please do my homework' type of question? Also this is not hw. This is part of hackreactor's prep course, I am doing to teach myself JS. – Vikrant Singh Commented May 3, 2017 at 21:23
Add a ment  | 

4 Answers 4

Reset to default 6

Check to see if the first character is a -. If so, b is your first numeral and should be negative:

function sumDigits(num) {
  return num.toString().split("").reduce(function(a, b){
    if (a == '-') {
      return -parseInt(b);
    } else {
      return parseInt(a) + parseInt(b);
    }
  });
}

You could use String#match instead of String#split for a new array.

function sumDigits(num) {
    return num.toString().match(/-?\d/g).reduce(function(a, b) {
        return +a + +b;
    });
}

console.log(sumDigits(1148)); // 14
console.log(sumDigits(-316)); // 4

Somebody who is looking for a solution without reduce functions etc. can take this approach.

function sumDigits(num) {
        
        var val = 0, remainder = 0;
            
        var offset = false;
        if (num <0) {
            offset = true;
            num = num * -1;
        }
        
        while (num) {
            remainder = num % 10;
            val += remainder;
            num = (num - remainder) / 10;
        }

        if (offset) {
            val -= 2 * remainder;//If the number was negative, subtract last 
                                 //left digit twice
        }

        return val;

    }

    var output = sumDigits(-348);
    console.log(output); 
    output = sumDigits(348);
    console.log(output);
    output = sumDigits(1);
    console.log(output);

//Maybe this help: // consider if num is negative:
function sumDigits(num){

  let negativeNum = false;
  if(num < 0){
    num = Math.abs(num);
    negativeNum = true;
  }
  let sum = 0;
  let stringNum = num.toString()
  for (let i = 0; i < stringNum.length; i++){
    sum += Number(stringNum[i]);
  }
    if(negativeNum){
      return sum - (Number(stringNum[0]) * 2);
   // stringNum[0] has the "-" sign so deduct twice since we added once    
  } else {
      return sum;
  }
}

本文标签: javascriptSum of all digits of a numberStack Overflow