AlgoDaily 11: Sum Digits Until One
https://algodaily.com/challenges/sum-digits-until-one
“We’re provided a positive integer num. Can you write a method to repeatedly add all of its digits until the result has only one digit?
Here’s an example: if the input was 49, we’d go through the following steps:”
// start with 49
4 + 9 = 13
// move onto 13
1 + 3 = 4
This seems to mostly be an issue of type juggling. If we’re careful with types, then all we have to do is keep breaking down the string of the number into single digit characters, sum those as numbers and set the original number to the string of that number.
function sumDigits(num) {
while (String(num).length > 1) {
num = [...String(num)].reduce((sum, d) => {
return sum + Number(d);
}, 0);
}
return num;
}
(sumDigits
is a bad name for this function, but is the one suggested.)
The solution on Algo Daily is pretty much the same.
Algo Daily also suggests using the congruence formula for a digital root, which avoids any iteration:
function digitalRoot(num) {
if (num === 0) {
return 0;
}
if (num % 9 === 0) {
return 9;
}
return num % 9;
}