Add Digits
LeetCode 258 | Difficulty: Easyβ
EasyProblem Descriptionβ
Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.
Example 1:
Input: num = 38
Output: 2
Explanation: The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
Example 2:
Input: num = 0
Output: 0
Constraints:
- `0 <= num <= 2^31 - 1`
Follow up: Could you do it without any loop/recursion in O(1) runtime?
Topics: Math, Simulation, Number Theory
Approachβ
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
When to use
Problems with clear mathematical structure, counting, number properties.
Solutionsβ
Solution 1: C# (Best: 52 ms)β
| Metric | Value |
|---|---|
| Runtime | 52 ms |
| Memory | N/A |
| Date | 2018-04-12 |
Solution
public class Solution {
public int AddDigits(int num) {
if(num/10==0) return num;
else
{
int ret = 0;
while(num!=0)
{
int rem = num%10;
ret = ret+rem;
num/=10;
}
if(ret/10==0) return ret;
else return AddDigits(ret);
}
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- LeetCode provides 4 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: A naive implementation of the above process is trivial. Could you come up with other methods?
Hint 2: What are all the possible results?
Hint 3: How do they occur, periodically or randomly?
Hint 4: You may find this Wikipedia article useful.