Skip to content Skip to sidebar Skip to footer

Split Negative Number Apart And Then Sum Together

i'm trying to write a function to sum the individual digits of a negative and positive number. I get stuck on how to sum the negative number after I've split the digits apart. Can

Solution 1:

Use String#match with regex which matches optional - with the digit.

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);

Solution 2:

You could set nextIsMinus to true, in case the current char is a -, like so:

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));

Post a Comment for "Split Negative Number Apart And Then Sum Together"