Skip to content Skip to sidebar Skip to footer

Sum Of All Digits Of A Number

Given Problem: Write a function called 'sumDigits'. Given a number, 'sumDigits' returns the sum of all its digits. var output = sumDigits(1148); console.log(output); // --> 14

Solution 1:

Check to see if the first character is a -. If so, b is your first numeral and should be negative:

functionsumDigits(num) {
  return num.toString().split("").reduce(function(a, b){
    if (a == '-') {
      return -parseInt(b);
    } else {
      returnparseInt(a) + parseInt(b);
    }
  });
}

Solution 2:

You could use String#match instead of String#split for a new array.

functionsumDigits(num) {
    return num.toString().match(/-?\d/g).reduce(function(a, b) {
        return +a + +b;
    });
}

console.log(sumDigits(1148)); // 14console.log(sumDigits(-316)); // 4

Solution 3:

Somebody who is looking for a solution without reduce functions etc. can take this approach.

functionsumDigits(num) {
        
        var val = 0, remainder = 0;
            
        var offset = false;
        if (num <0) {
            offset = true;
            num = num * -1;
        }
        
        while (num) {
            remainder = num % 10;
            val += remainder;
            num = (num - remainder) / 10;
        }

        if (offset) {
            val -= 2 * remainder;//If the number was negative, subtract last //left digit twice
        }

        return val;

    }

    var output = sumDigits(-348);
    console.log(output); 
    output = sumDigits(348);
    console.log(output);
    output = sumDigits(1);
    console.log(output);

Solution 4:

//Maybe this help: // consider if num is negative:functionsumDigits(num){

  let negativeNum = false;
  if(num < 0){
    num = Math.abs(num);
    negativeNum = true;
  }
  let sum = 0;
  let stringNum = num.toString()
  for (let i = 0; i < stringNum.length; i++){
    sum += Number(stringNum[i]);
  }
    if(negativeNum){
      return sum - (Number(stringNum[0]) * 2);
   // stringNum[0] has the "-" sign so deduct twice since we added once    
  } else {
      return sum;
  }
}

Post a Comment for "Sum Of All Digits Of A Number"