Add Digits — Solution in Python, Java & C++
Add Digits solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem, asked at Amazon and Adobe.
Add Digits is an easy coding problem on math, simulation and number theory, asked in Amazon, Adobe, Capgemini and Cognizant interviews.
- Difficulty: Easy
- Topics: Math, Simulation, Number Theory
- Asked at: Amazon, Adobe, Capgemini, Cognizant, Mphasis
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a non-negative integer num, repeatedly add all of its digits until the result has only one digit, and return that digit.
Example 1
Input: num = 38
Output: 2
Explanation: 3+8 = 11, then 1+1 = 2. Two has one digit, so stop.
Example 2
Input: num = 0
Output: 0
Example 3
Input: num = 9999
Output: 9
Explanation: 9+9+9+9 = 36, then 3+6 = 9.
Constraints
0 <= num <= 2^31 - 1
Follow-up: Can you do it in O(1) time without any loop?
Hints for Add Digits
Hint 1
The straightforward solution simply loops the summation until one digit remains.
Hint 2
Summing digits never changes a number's remainder modulo 9, because 10 ≡ 1 (mod 9).
Hint 3
That gives a closed form: 0 for 0, otherwise
1 + (num - 1) % 9.
How to solve Add Digits
Repeated digit summing computes the digital root, and a number and its digit sum are congruent modulo 9 because 10 ≡ 1 (mod 9). The answer is therefore num mod 9, with 9 in place of 0 for positive inputs.
Approach
- Return
0fornum == 0. - Otherwise return
1 + (num - 1) % 9.
Why it works
Since 10^k ≡ 1 (mod 9), Σ dᵢ·10^i ≡ Σ dᵢ (mod 9) — digit summing preserves the residue mod 9. The process stops at a single digit, and among 1…9 only one digit has each residue, so the final digit is determined by num mod 9. The 1 + (num - 1) % 9 form maps residue 0 to 9 instead of 0.
Complexity
- Time —
O(1) - Space —
O(1)
Pitfalls
- Writing
num % 9returns0for multiples of nine; the digital root of18is9. - The loop-until-one-digit version is also correct and only slightly slower — the closed form is the interview flourish.
Reference solution
Python
def addDigits(num: int) -> int:
if num == 0:
return 0
return 1 + (num - 1) % 9Java
public static int addDigits(int num) {
if (num == 0) return 0;
return 1 + (num - 1) % 9;
}C++
int addDigits(int num) {
if (num == 0) return 0;
return 1 + (num - 1) % 9;
}JavaScript
var addDigits = function(num) {
if (num === 0) return 0;
return 1 + (num - 1) % 9;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.