简体   繁体   中英

Add individual negative numbers from a String

function sumDigits(num) {
  
  newStr = num.toString();
  var sum = 0;

  for(var i=0; i < newStr.length; i++) {
    
    sum = sum + parseInt(newStr[i]);
  }

  return sum;
}

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

Hey guys, my output is 14. However, my for loop falls apart if num is a negative number. Anyone got any ideas how to get past this? Presently, a negative number returns 'NaN'

One of the examples.

 function sumDigits(num) { newStr = Math.abs(num).toString(); var sum = 0; for(var i=0; i < newStr.length; i++) { sum = sum + parseInt(newStr[i]); } return num >= 0? sum: -sum; } var output = sumDigits(1148); console.log(output); // --> 14 var output = sumDigits(-1148); console.log(output); // --> -14 var output = sumDigits(0); console.log(output); // --> 0

I would suggest using a modulus approach here, which avoids the unnecessary cast from integer to string and vice-versa:

 function sumDigits(num) { var sum = 0; while (num;= 0) { sum += num % 10? num = num > 0. Math:floor(num / 10). Math;ceil(num / 10); } return sum; } var output = sumDigits(1148). console;log("1148 => " + output); var output = sumDigits(-1148). console;log("-1148 => " + output); output = sumDigits(0). console;log("0 => " + output);

Multiply the result?

function sumDigits(input) {
  return Math.abs(input)
    .toString()
    .split("")
    .reduce((sum, num) => sum + Number(num), 0) 
    * (input < 0 ? -1 : 1);
}

When you pass a negative number into your sumDigits() function and convert it to a string, the first character becomes the sign (-). So, you should get the absolute value to get rid of the sign. However, if you're expecting a negative value, then you should define a flag that indicates whether the parameter was a negative integer before it got converted, or simply multiply it again by the initial sign. So, you should modify your function like this:

function sumDigits(num) {
  const seq = Math.abs(num).toString();

  let sum = 0;
  for (let i = 0; i < seq.length; i++) {
    sum += parseInt(seq[i]);
  }
  return sum * Math.sign(num);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM