
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.
1#include <iostream>
2
3int addDigits(int num) {
4 while (num >= 10) {
5 int sum = 0;
6 while (num > 0) {
7 sum += num % 10;
8 num /= 10;
9 }
10 num = sum;
11 }
12 return num;
13}
14
15int main() {
16 int num = 38;
17 std::cout << addDigits(num) << std::endl;
18 return 0;
19}Similar to C, C++ uses the same process of using loops to repeatedly sum the digits of the number until a single-digit number is achieved.
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
This C solution uses modulo 9 to calculate the digit root. This gives us a constant time solution which is highly efficient.