#258
Add Digits
EasyMathSimulationNumber TheoryMathematical PropertiesModulo Operations
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal approach uses a mathematical property known as the digital root, which allows us to compute the result in constant time without loops or recursion. This is based on the fact that the result can be derived using modulo operations.
⚙️
Algorithm
2 steps- 1Step 1: If num is 0, return 0.
- 2Step 2: If num is not 0, return 1 + (num - 1) % 9. This formula derives from properties of numbers in base 10.
solution.py6 lines
1# Full working Python code
2
3def add_digits(num):
4 if num == 0:
5 return 0
6 return 1 + (num - 1) % 9ℹ
Complexity note: The time complexity is O(1) because we are using a constant-time mathematical formula to compute the result, and space complexity is O(1) since we are not using any additional data structures.
- 1The digital root can be computed in constant time using properties of numbers.
- 2Understanding the relationship between digits and modulo operations can simplify problems significantly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.