Sum all the digits of a number Javascript

后端 未结 4 2093
囚心锁ツ
囚心锁ツ 2020-11-27 06:21

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 calcul

4条回答
  •  眼角桃花
    2020-11-27 06:27

    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.

提交回复
热议问题