Problem Description
Given a non-negative integer num, repeatedly sum its digits until the result is a single digit. Return that single-digit number.
Key Insights
- The problem can be solved by repeatedly adding digits until a single digit is obtained.
- A mathematical trick exists (digital root) that allows solving the problem in O(1) time without any loops or recursion.
- The digital root of a non-zero number is 9 if the number is divisible by 9, otherwise it is num modulo 9.
- Special handling is needed for the edge case where num is 0.
Space and Time Complexity
Time Complexity: O(1) Space Complexity: O(1)
Solution
The solution uses the mathematical property known as the digital root. Instead of repeatedly summing the digits using loops or recursion, the digital root can be calculated using a simple formula:
- If num is 0, the answer is 0.
- Otherwise, if num % 9 is 0, return 9.
- Else, return num % 9. This approach works because the digital root formula directly gives the result of repeatedly summing the digits until a single digit is obtained.