Add digits till the result has one digit

Problem Link : Add Digits Till Result Has One Digit


Problem Statement

Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.


Examples

Example 1:

Example 2:


Constraints


Intuition

The naive approach would involve repeatedly summing the digits using a loop or recursion until a single-digit result is obtained.

However, this can be optimized using a mathematical insight called the digital root, which is based on modulo arithmetic in base 10:

The digital root of a number is the value obtained by repeatedly summing the digits of the number until a single-digit number is obtained.

For base 10 numbers, the formula for the digital root is:

If num == 0 → return 0  
If num % 9 == 0 → return 9  
Else → return num % 9

This is known as the digital root formula.


Approach

We use a constant time approach (O(1)) based on the modulo 9 property:

  1. If the number is 0, return 0.

  2. If the number is divisible by 9, return 9.

  3. Otherwise, return num % 9.


Java Code

class Solution {
    public int addDigits(int num) {
        if (num == 0) return 0;
        if (num % 9 == 0) return 9;
        return num % 9;
    }
}

Alternatively, the formula can be compressed into one line:

class Solution {
    public int addDigits(int num) {
        return (num == 0) ? 0 : (num % 9 == 0 ? 9 : num % 9);
    }
}

Dry Run

Input: num = 38

Input: num = 18

Input: num = 0


Time Complexity

Space Complexity


Conclusion

This problem, although appearing iterative, can be solved in constant time using the digital root technique. The modulo-based solution is efficient, elegant, and well-suited for large input values.