
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.
1public class AddDigitsIterative {
2 public static int addDigits(int num) {
3 while (num >= 10) {
4 int sum = 0;
5 while (num > 0) {
6 sum += num % 10;
7 num /= 10;
8 }
9 num = sum;
10 }
11 return num;
12 }
13
14 public static void main(String[] args) {
15 int num = 38;
16 System.out.println(addDigits(num));
17 }
18}In Java, the approach involves looping through the digits, summing them, and using the same integer operations to yield a reduced number until it is a single digit.
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.
1using System;
2
public class AddDigitsMath {
public static int AddDigits(int num) {
if (num == 0) return 0;
return (num % 9 == 0) ? 9 : num % 9;
}
public static void Main() {
int num = 38;
Console.WriteLine(AddDigits(num));
}
}The C# implementation builds on the efficient technique of digit root calculation using modulo arithmetic.