Approach: The solution repeatedly extracts each digit using the modulo (%) operator and computes their sum. If the resulting sum contains more than one digit, the same process is repeated until a single-digit value is obtained.
This iterative approach is easy to understand and works efficiently for any non-negative integer without using additional data structures.
Java Solution:
public class AddDigits {
public static int addDigits(int number) {
while (number >= 10) {
int digitSum = 0;
while (number > 0) {
digitSum += number % 10;
number /= 10;
}
number = digitSum;
}
return number;
}
public static void main(String[] args) {
int number = 9875;
int result = addDigits(number);
System.out.println("Single Digit Result: " + result);
}
}Output: Single Digit Result: 2
Time Complexity: O(d × k), where d is the number of digits and k is the number of iterations required to reduce the number to a single digit. In practice, the number of iterations is very small.
Space Complexity: O(1), as only a few variables are used irrespective of the input size.
Key Interview Points: • The modulo (%) operator is commonly used to extract digits from a number. • The algorithm repeatedly processes digits until a single-digit result is obtained. • An optimized mathematical approach using the Digital Root concept can solve the problem in O(1) time using the formula: result = (number == 0) ? 0 : 1 + (number - 1) % 9