javascript - Return sum of a number (positive or negative) - Stack Overflow

I need to make a function that takes a number and returns sum of it's digits, if the number is neg

I need to make a function that takes a number and returns sum of it's digits, if the number is negative the first digit should be considered negative when adding numbers, this is what I have:

var arrx = [];
var oper;
var others = 0;

function sumDigits(num) {
    // your code here
    var y = num.toString();
    var c = y.split("");
    c.forEach((h) => arrx.push(Number(h)) );
    if (num < 0){
        oper = -arrx[0];
        for (var z = 1; z < arrx.length; z++){
            others += arrx[z];
        }

        return others + oper;
    }

    return arrx.reduce((a,b) => a+b);
}

sumDigits(1234);

When given negative number, function returns NaN, what's the problem ?

I need to make a function that takes a number and returns sum of it's digits, if the number is negative the first digit should be considered negative when adding numbers, this is what I have:

var arrx = [];
var oper;
var others = 0;

function sumDigits(num) {
    // your code here
    var y = num.toString();
    var c = y.split("");
    c.forEach((h) => arrx.push(Number(h)) );
    if (num < 0){
        oper = -arrx[0];
        for (var z = 1; z < arrx.length; z++){
            others += arrx[z];
        }

        return others + oper;
    }

    return arrx.reduce((a,b) => a+b);
}

sumDigits(1234);

When given negative number, function returns NaN, what's the problem ?

Share Improve this question edited Apr 12, 2018 at 1:40 Cœur 38.8k25 gold badges206 silver badges279 bronze badges asked Jan 29, 2017 at 22:38 user7451361user7451361 2
  • Why do you push the digits to an array when c is already one? – Code-Apprentice Commented Jan 29, 2017 at 23:03
  • I suggest developing an algorithm that works directly with numbers rather than converting the number to a String. Can you think of a way to get the ones digit from a number? How do you get the rest of the number other than the ones digit? – Code-Apprentice Commented Jan 29, 2017 at 23:04
Add a ment  | 

2 Answers 2

Reset to default 1

Use optimized and short version of sumDigits() function:

function sumDigits(num) {
  var isNeg = num < 0,   // check whether the number is negative
      numbers = (isNeg? String(num).slice(1) : String(num)).split('').map(Number);
  if (isNeg) numbers[0] *= -1;   // 'recovering' the number's sign

  return numbers.reduce(function(a,b){ return a + b; });
}

console.log(sumDigits(1234));
console.log(sumDigits(-951));

In case of negative number, the first char is '-' the minus symbol. When you are trying to convert it to number, you are getting NaN. After that if you try to add NaN to any number the result would be NaN.

As a resolution, you need to ignore the first digit if the number is negative.

So, you can make a code change like

if(z === 1){
    others = others - arrx[z];
    }else{
     others += arrx[z];
      }

and also changing the return in case of negative numbers to return others;

Following code should work.

var arrx = [];
var oper;
var others = 0;

function sumDigits(num) {
 // your code here

var y = num.toString();

var c = y.split("");

c.forEach((h) => arrx.push(Number(h)) );

if (num < 0){


for (var z = 1; z < arrx.length; z++){

  if(z === 1){
    others = others - arrx[z];
    }else{
     others += arrx[z];
      }

}

return others;
}

return arrx.reduce((a,b) => a+b);

}
console.log(sumDigits(-1234));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745501002a4630414.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信