0

I have a function that returns the sum of all its digits For both POSITIVE and NEGATIVE numbers.

I used split method and converted it to string first and then used reduce to add them all. If the number is negative, the first digit should count as negative.

function sumDigits(num) {
var output = [],
sNum = num.toString();

for (var i = 0; i < sNum.length; i++) {
  output.push(sNum[i]);
}

return output.reduce(function(total, item){
   return Number(total) + Number(item);
 });

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

var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4

Instead of returning the sum, it returned 4592 -1264

Am I doing it right or do I need to use split function? Or is there any better way to do this?

Sorry newbie here.

  • `output.push(sNum);` what do you think that is doing? – epascarello Jun 21 '17 at 00:42
  • I think you will find your answer [here](https://stackoverflow.com/questions/7784620/javascript-number-split-into-individual-digits). – Ozan Jun 21 '17 at 00:44
  • You need to push `sNum[i]`. And skip the `-`. –  Jun 21 '17 at 00:45
  • @Chris G sNum[i] works however for negative numbers it did NOT work. especially if you put negative number infront of the digits. –  Jun 21 '17 at 00:57

1 Answers1

0

I think you'll have to treat it as a string and check iterate over the string checking for a '-' and when you find one grab two characters and convert to an integer to push onto the array. Then loop over the array and sum them. Of course you could do that as you go and not bother pushing them on the array at all.

function sumDigits(num) {
  num = num + '';
  var output = [];
  var tempNum;
  var sum = 0;

  for (var i = 0; i < num.length; i++) {
    if (num[i] === '-') {
        tempNum = num[i] + num[i + 1];
        i++;
    } else {
      tempNum = num[i];
    }
    
    output.push(parseInt(tempNum, 10));
  }
  
  
  for (var j = 0; j < output.length; j++) {
    sum = sum + output[j];
  }

  return sum;
}

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

var output2 = sumDigits(-316);
console.log(output2); // --> MUST RETURN 4
Russell
  • 476
  • 2
  • 10