Add Digits - Problem
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Follow up: Could you do it without any loop/recursion, in O(1) runtime?
Input & Output
Example 1 — Two Digit Number
$
Input:
num = 38
›
Output:
2
💡 Note:
3 + 8 = 11, then 1 + 1 = 2. Since 2 has only one digit, return 2.
Example 2 — Single Digit
$
Input:
num = 0
›
Output:
0
💡 Note:
0 already has only one digit, so return 0 immediately.
Example 3 — Multiple Iterations
$
Input:
num = 999
›
Output:
9
💡 Note:
9 + 9 + 9 = 27, then 2 + 7 = 9. Since 9 has only one digit, return 9.
Constraints
- 0 ≤ num ≤ 2³¹ - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Multi-digit number to process
2
Process
Sum digits repeatedly until single digit
3
Output
Final single digit result
Key Takeaway
🎯 Key Insight: The digital root follows a modulo 9 pattern, enabling O(1) solution
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code