I saw this javascript snippet/ question here The best answer is

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

I'm trying to understand how it works. I can understand some of the lines but it's confusing though.

What I can understand is

var remainder = number % 10;
var sum = remainder;

return the remainder of the number. In other words, if the number is 145 and it's divided by 10, the remainder is 5. Therefore, the sum is 5. Next,

if(number >= 10) {

The number needs to be more than or equal to 10 because you cannot add up a single digit by itself, therefore '10' is the minimum in which you can add two digits together. Next,

var rest = Math.floor(number / 10); 

145 divided by 10 is 14.5. Math.floor will round it down to 14. Therefore, rest = 14. Next,

sum += sumDigits(rest);

Since rest is 14, that means that sumDigits is 14. So since the sum is 5, it adds itself to the rest. In other words, sum = 5 + 14. In conclusion, the sum is 19.

That's why it's confusing for me because it doesn't add up when 145 = 1 + 4 + 5 = 10. In other words, the sum should be 10, not 19?!?!?????

share|improve this question
    
Read about recursion - that is the "point" of this function - en.wikipedia.org/wiki/Recursion_(computer_science) – Ron Dadon 10 mins ago
    
Since rest is 14, that means that sumDigits is 14 No, since rest is 14, that means that sumDigits(14) is 5. – torazaburo 9 mins ago

Let me break it down for you:

sumDigits(145)
5 + sumDigits(14)
5 + 4 + sumDigits(1)
5 + 4 + 1 => 10
share|improve this answer

The funciton works fine as expected.

Once you get 19 in the end, it runs it again in same function, as 19 is greater than 10. So 1+9 would equal to 10.

share

I think the key here is

Since rest is 14, that means that sumDigits is 14.

If you ran just sumDigit(14), you would sum 1 and 4 = 5. Then 5 is added to the original 5 in 145

When I was thinking this through, I refactored it a bit, which helped me understand what's going on. Here's another way of thinking about it:

function sumDigits(number) {
    var integerDigit = number % 10;

    // If there are digits remaining (i.e. not a single digit number)
    if(number >= 10) {
        // Return the current digit plus sumDigits of remaining digits
        return integerDigit + sumDigits(Math.floor(number / 10));
    }

    // If it is a single digit, just return the number
    return number;
}
share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.