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?!?!?????
rest
is14
, that means thatsumDigits(14)
is5
. – torazaburo 9 mins ago