Hodorogea Alexandru
Hodorogea Alexandru

Reputation: 469

Sum all the digits of a number Javascript

I am newbie.

I want to make small app which will calculate the sum of all the digits of a number.

For example, if I have the number 2568, the app will calculate 2+5+6+8 which is equal with 21. Finally, it will calculate the sum of 21's digits and the final result will be 3 .

Please help me

Upvotes: 27

Views: 149907

Answers (8)

Dawood Valeed
Dawood Valeed

Reputation: 155

you can use this function and pass your number to it:

const solution = (n) => {
    const arr = `${n}`
    let sum = 0;
    for (let index = 0; index < arr.length; index++) {
        sum += parseInt(arr[index])
    }
    return sum;
}

Upvotes: 0

Ankush Tiwari
Ankush Tiwari

Reputation: 33

You could do it this way.

function sums(input) {
    let numArr = input.toString().split('');
    let sum = numArr.reduce((a, b) => Number(a) + Number(b));
    return sum < 10 ? sum : sums(sum);
}

Upvotes: 2

yogski
yogski

Reputation: 301

Expanding upon @fethe 's answer, this sumOfDigit function is able to handle large number or BigInt

function sumOfDigits(n) { 
  return (Number.isSafeInteger(n)) ? (--n % 9) + 1 : Number((--n % 9n) + 1n);
}

console.log(sumOfDigits(101)); // 2
console.log(sumOfDigits(84932)); // 8
console.log(sumOfDigits(900000000000000000000000009n)); // 9

Upvotes: 0

WesleyAC
WesleyAC

Reputation: 553

With mathy formula:

function sumDigits(n) { 
    return (--n % 9) + 1;
}

Without mathy formula:

function sumDigits(n) {
    if (typeof n !== 'string') {
        n = n.toString();
    }    
    if (n.length < 2) {
        return parseInt(n);
    }
​
    return sumDigits(
        n.split('')
         .reduce((acc, num) => acc += parseInt(num), 0)
    );
}

Upvotes: 5

Envy Hion
Envy Hion

Reputation: 184

let's try recursivity

function sumDigits(n) {
  if (n < 10) return n
  return sumDigits(n % 10 + sumDigits(Math.floor(n / 10)))
}

sumDigits(2) // 2
sumDigits(2568) // 3

Upvotes: 3

Konard
Konard

Reputation: 3034

The sum of digits can be calculated using that function (based on other answers):

function sumDigits(n) {
    let sum = 0;
    while (n) {
        digit = n % 10;
        sum += digit;
        n = (n - digit) / 10;
    }
    return sum;
}

If you really need to sum the digits recursively there is recursive version of the function:

function sumDigitsRecursively(n) {
    let sum = sumDigits(n);
    if (sum < 10)
        return sum;
    else
        return sumDigitsRecursively(sum);
}

The sumDigitsRecursively(2568) expression will be equal to 3. Because 2+5+6+8 = 21 and 2+1 = 3.

Note that recursive solution by @FedericoAntonucci should be more efficient, but it does not give you intermediate sum of digits if you need it.

Upvotes: 2

fethe
fethe

Reputation: 697

How about this simple approach using modulo 9 arithmetic?

function sumDigits(n) {
  return (n - 1) % 9 + 1;
}

Upvotes: 40

Nina Scholz
Nina Scholz

Reputation: 386660

Basically you have two methods to get the sum of all parts of an integer number.

  • With numerical operations

    Take the number and build the remainder of ten and add that. Then take the integer part of the division of the number by 10. Proceed.

var value = 2568,
    sum = 0;

while (value) {
    sum += value % 10;
    value = Math.floor(value / 10);
}

console.log(sum);

  • Use string operations

    Convert the number to string, split the string and get an array with all digits and perform a reduce for every part and return the sum.

var value = 2568,
    sum = value
        .toString()
        .split('')
        .map(Number)
        .reduce(function (a, b) {
            return a + b;
        }, 0);

console.log(sum);


For returning the value, you need to addres the value property.

rezultat.value = sum;
//      ^^^^^^

function sumDigits() {
    var value = document.getElementById("thenumber").value,
        sum = 0;

  while (value) {
      sum += value % 10;
      value = Math.floor(value / 10);
  }
  
  var rezultat = document.getElementById("result");
  rezultat.value = sum;
}
<input type="text" placeholder="number" id="thenumber"/><br/><br/>
<button onclick="sumDigits()">Calculate</button><br/><br/>
<input type="text" readonly="true" placeholder="the result" id="result"/>

Upvotes: 55

Related Questions