Recursively Sum All Digits in a Number

I recently started answering questions on StackOverflow for fun. I figured since I’m taking the time to answer questions, I may as well post that content on my blog. Here’s my first post of this type, an easy recursion problem using javascript.

Problem

Sum all the digits of a number using recursion.
Example Input: 54673
Example Output: 25 (5 + 4 + 6 + 7 + 3)

Solution

function sumDigits(number) {
    var remainder = number % 10;
    var sum = remainder;
    if(number >= 10) {
        var rest = Math.floor(number / 10);
        sum += sumDigits(rest);
    }
    return sum;
}

Answered here.

Leave a Reply

Your email address will not be published. Required fields are marked *