
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.
1def add_digits(num):
2 while num >= 10:
3 sum = 0
4 while num > 0:
5 sum += num % 10
6 num //= 10
7 num = sum
8 return num
9
10print(add_digits(38))Python's implementation uses loops to compute the sum of the digits repeatedly until a single-digit number is obtained.
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.
1#include <iostream>
2
int addDigits(int num) {
if (num == 0) return 0;
if (num % 9 == 0) return 9;
return num % 9;
}
int main() {
int num = 38;
std::cout << addDigits(num) << std::endl;
return 0;
}In C++, we use an identical approach to solve the problem in optimal time by checking conditions around the modulo operation.