将负数拆分,然后加在一起

时间:2016-11-21 18:53:40

标签: javascript

我试图写一个函数来对负数和正数的各个数字求和。在我将数字分开之后,我被困在如何将负数加起来。我可以逃避' - '签到(-538)返回['-5', '3', '8' ]而不是[ '-', '5', '3', '8' ]或者我是否采取了解决此问题的错误方法?



function sumDigits(num) {
    var count = 0;
    
    var intermediate =  num.toString().split('')
    
    for(var i = 0; i < intermediate.length; i++){
        count += parseInt(intermediate[i])
        
}
   return count; 
}


var positive = sumDigits(2309);
console.log(positive); // --> 14


var negative = sumDigits(-8525);
console.log(negative); // --> 4
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:5)

String#match与带有数字的可选-匹配的正则表达式一起使用。

function sumDigits(num) {
  var count = 0;
  var intermediate = num.toString().match(/-?\d/g);
  for (var i = 0; i < intermediate.length; i++) {
    count += parseInt(intermediate[i])
  }
  return count;
}


var positive = sumDigits(2309);
console.log(positive);


var negative = sumDigits(-8525);
console.log(negative);

答案 1 :(得分:0)

如果当前字符为nextIsMinus,您可以将-设置为true,如下所示:

&#13;
&#13;
function sumDigits(num)
{
    var count = 0;
    var intermediate =  num.toString().split('')
    var nextIsMinus = false;
    for(var i = 0; i < intermediate.length; i++)
    {
        if(intermediate[i] == "-")
        {
            nextIsMinus = true;
        } else
        {
            if(nextIsMinus)
            {
                count -= parseInt(intermediate[i]);
                nextIsMinus = false;
            } else
            {
                count += parseInt(intermediate[i]);
            }
        }
    }
    return count; 
}


console.log(sumDigits(2309));
console.log(sumDigits(-8525));
&#13;
&#13;
&#13;