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
Add Digits: Keep Summing Until Single DigitMulti-digit38Sum digits3 + 8 = 11Still > 9Sum again1 + 1 = 2Single digit!Result2Algorithm: Repeat digit summation until single digit remainsTwo Approaches Available:1. Simulation: O(log n) - Keep summing2. Math Formula: O(1) - Use (n-1) % 9 + 1
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
Asked in
Adobe 15 Microsoft 12 Amazon 8
195.0K Views
Medium Frequency
~10 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen