Skip to main content

Add Digits

LeetCode 258 | Difficulty: Easy​

Easy

Problem 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)​

MetricValue
Runtime52 ms
MemoryN/A
Date2018-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​

ApproachTimeSpace
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.