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
From Simulation to Mathematical FormulaSimulation Approach1. Extract digits: 3, 82. Sum: 3 + 8 = 113. Extract digits: 1, 14. Sum: 1 + 1 = 25. Result: 2 (single digit)Time: O(log n), Space: O(1)Mathematical FormulaDigital Root Pattern:1,2,3,4,5,6,7,8,9,1,2,3...Formula: 1 + (n-1) % 9For 38: 1 + (38-1) % 9 = 2Time: O(1), Space: O(1)Why Does the Formula Work?โ€ข Any number โ‰ก sum of its digits (mod 9)โ€ข Repeatedly adding digits is like taking mod 9โ€ข Special case: when n % 9 = 0, result should be 9 (not 0)โ€ข Formula 1 + (n-1) % 9 handles this elegantly๐ŸŽฏ Key Insight: Mathematical properties can transform iterative problems into constant-time solutions!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space

n
2n
โœ“ Linear Space

Constraints

  • 0 โ‰ค num โ‰ค 231 - 1
  • Follow-up: Could you do it without any loop/recursion in O(1) runtime?
Asked in
Adobe 15 Microsoft 12 Apple 8 Google 6
89.6K Views
Medium Frequency
~15 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