Add Digits - Problem
Given an integer num, you need to repeatedly add all its digits until the result has only one digit, and return it.
This is a fascinating number theory problem! For example, if you start with 38:
- First iteration:
3 + 8 = 11 - Second iteration:
1 + 1 = 2 - Result:
2(single digit achieved!)
The process continues until you reach a single digit (0-9). This concept is closely related to the digital root in mathematics.
Goal: Find the final single digit after repeatedly summing all digits of the given number.
Input & Output
example_1.py โ Basic Case
$
Input:
38
โบ
Output:
2
๐ก Note:
3 + 8 = 11, then 1 + 1 = 2. Since 2 is a single digit, we return 2.
example_2.py โ Single Digit
$
Input:
0
โบ
Output:
0
๐ก Note:
0 is already a single digit, so we return 0 immediately.
example_3.py โ Larger Number
$
Input:
999
โบ
Output:
9
๐ก Note:
9 + 9 + 9 = 27, then 2 + 7 = 9. Since 9 is a single digit, we return 9.
Visualization
Tap to expand
Understanding the Visualization
1
Simulate the Process
Start with any number and repeatedly add its digits
2
Observe the Pattern
Digital roots cycle through 1,2,3,4,5,6,7,8,9,1,2,3...
3
Connect to Modulo 9
The pattern aligns with n mod 9, with special handling for multiples of 9
4
Apply the Formula
Use 1 + (n-1) % 9 for instant O(1) calculation
Key Takeaway
๐ฏ Key Insight: The digital root is mathematically equivalent to 1 + (n-1) mod 9, allowing us to skip simulation entirely!
Time & Space Complexity
Time Complexity
O(1)
Single mathematical operation, constant time
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space
โ Linear Space
Constraints
- 0 โค num โค 231 - 1
- Follow-up: Could you do it without any loop/recursion in O(1) runtime?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code