
Sponsored
Sponsored
The iterative approach involves summing the digits of the number repeatedly until the sum becomes a single-digit number. This is a straightforward approach and uses basic loops to repeatedly process the digits of the number.
1function addDigits(num) {
2 while (num >= 10) {
3 let sum = 0;
4 while (num > 0) {
5 sum += num % 10;
6 num = Math.floor(num / 10);
7 }
8 num = sum;
9 }
10 return num;
11}
12
13console.log(addDigits(38));The JavaScript solution also relies on loops to process and sum the digits until a single digit is left.
The mathematical approach leverages a known number theory result related to digit root which can be deduced using modulo 9 arithmetic. The result for the repeated digit sum is equivalent to the number modulo 9, except that when the number is zero it should remain zero.
1public
Java uses similar logic, ensuring that the mathematical reduction via modulo provides the result in constant time.