Skip to content Skip to sidebar Skip to footer

Sum Of The Digits Of A Number Javascript

I saw a bunch of other posts on this topic but none in javascript. here is my code. var theNumber = function digitAdd (base, exponent) { var number = 1; for (i=0; i < ex

Solution 1:

The second function uses the modulo operator to extract the last digit:

1236%10=1236-10*floor(1236/10)=1236-1230=6

When the last digit is extracted, it is subtracted from the number:

1236-6=1230

And the number is divided by 10:

1230/10=123

Each time this loop repeats, the last digit is chopped off and added to the sum.

The modulo operator returns the single digit if the left hand side is smaller than the right (which will happen for any 1-digit number), which is when the loop breaks:

  1 % 10
= 1

This is how the leading digit gets added to the total.


A less numeric alternative would be this:

functionsumDigits(number) {
  var str = number.toString();
  var sum = 0;

  for (var i = 0; i < str.length; i++) {
    sum += parseInt(str.charAt(i), 10);
  }

  return sum;
}

It does literally what you are trying to do, which is iterate over the digits of the number (by converting it to a string).

Solution 2:

i use it :)

var result = eval('123456'.replace(/(\d)(?=\d)/g, '$1+'));
alert(result); // 21

without eval

var result = '123456'.split('').reduce(function(a,b){ return +a+ +b; });
alert(result); // 21

Solution 3:

i use this :

'123456'.split('').map(function(e){returnparseInt(e)}).reduce(function(a,b){return a+b}); //21

Update (ES6 syntax) :

[...'123456'].map(e=>parseInt(e)).reduce((a,b)=>a+b); //21

Solution 4:

Not sure what you meant, In case you were asking about while loop..

The while statement continually executes a block of statements while a particular condition is true. Its syntax can be expressed as:

while (expression) {
     statement(s)
}

The while statement evaluates expression, which must return a boolean value. If the expression evaluates to true, the while statement executes the statement(s) in the while block. The while statement continues testing the expression and executing its block until the expression evaluates to false.

The while loop here is extracting digits one by one from the actual number and adding those. Try to do each step manually and you will get it.

Post a Comment for "Sum Of The Digits Of A Number Javascript"