Understand
30-second explanation
Build the interview-ready mental model before comparing implementations.
Extract digits with repeated % 10 and / 10 to get the one-pass sum. If the prompt wants the *repeated* sum until a single digit (the digital root), you can loop the digit-sum until n < 10 — or skip the loop entirely with the O(1) congruence formula: dr(n) = 1 + (n − 1) % 9 for n > 0.
Interview contextWhat is testedWhere candidates slipHow to stand outExplore interview contextHide interview context
What's being tested
Whether you extract digits with clean modular arithmetic instead of string conversion, and whether you know the digital root has a closed form rather than needing a nested loop.
Where candidates slip
Writing `n % 9` for the digital root (wrong for multiples of 9 and for 0), or forgetting the `n //= 10` and spinning forever.
How to stand out
Solve the literal sum in one pass, then volunteer that the *repeated* sum equals the digital root and reduces to `1 + (n − 1) % 9` in O(1) — and explain *why* via casting out nines.
Choose
Compare the available approaches
Use constraints and trade-offs to select the route you can defend in an interview.
Interactive decision treeInteractiveChoose the right approachFirst decision previewSum the digits of nSingle pass or repeated to one digit?SingleRepeatedExplore the full treeCollapse the tree
Learn & trace
Build each solution step by step
Move from the core idea to a visual trace, implementation, proof, and edge cases.
Approach 1 of 2
One-Pass Digit Extraction (Baseline)
1Hint 1Explore hintHide hint
How do you get the last digit of a number without converting it to text? Think about the remainder when you divide by 10.
2Hint 2Explore hintHide hint
`n % 10` is the last digit; `n / 10` (integer division) removes it. Loop until n becomes 0.
3Hint 3Explore hintHide hint
Accumulate `n % 10` into a sum, then assign `n = n / 10` each iteration. The loop runs once per digit.
A · Core idea
Repeatedly take the last digit with n % 10, add it to a running sum, then strip that digit with integer division n /= 10. Stop when n reaches 0.
Why modulo and integer division are the right tools. Base-10 positional notation means the last digit is the remainder modulo 10, and dividing by 10 (discarding the remainder) shifts every digit one place right — exactly like deleting the last character of the number. Two cheap arithmetic ops give you digit access without ever allocating a string.
Why the loop must update n. The terminating condition is n > 0, and the only thing that drives n toward 0 is the n /= 10. Drop that line and n never changes, so the loop spins forever — the single most common bug on this problem. Always pair the % 10 read with the /= 10 shrink.
Why you should take the absolute value for negatives. In Java, -123 % 10 is -3; in Python it's 7. Either way you don't want signed remainders polluting a digit sum, so normalize with abs(n) up front when the spec allows negatives.
Why string conversion is usually worse here. Converting to a string and summing int(ch) works and reads fine, but it allocates, and the arithmetic version is the one interviewers expect because it shows you can manipulate numbers directly. Reach for the string only when the value is arbitrary-precision and big-number division would be slow.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
n = 38Array state
iter 1
peel 8, sum = 8
11C · Code with teaching comments
Reference implementation previewpublic int sumOfDigits(int n) { n = Math.abs(n); int sum = 0; while (n > 0) { sum += n % 10; // last digitExplore the full codeHide the full code
D · Why it works and complexityO(log n) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
% 10 and /= 10 are the universal 'read the last digit, then drop it' pair. Internalize them and a whole family of problems — palindrome number, reverse integer, Armstrong number — uses the exact same two lines.
ComplexityO(log n) time, O(1) space — A number with d digits satisfies d ≈ log₁₀(n) + 1, and the loop runs once per digit, so the work is O(log n). Only a single accumulator is stored.
E · Edge cases and pitfalls3Forgetting `n /= 10`, causing an infinite loop.Explore edge casesHide edge cases
Pitfalls
- Forgetting `n /= 10`, causing an infinite loop.
- Not taking abs(n) when negatives are allowed — signed remainders break the sum.
- Converting to a string when the arithmetic version is cleaner and allocation-free.
Approach 2 of 2 · Optimal
Digital Root in O(1) (Optimal for the repeated sum)
1Hint 1Explore hintHide hint
Repeatedly summing digits preserves the value modulo 9 — adding digits is 'casting out nines'. Why might that be?
2Hint 2Explore hintHide hint
Every power of 10 is congruent to 1 mod 9 (10 ≡ 1, 100 ≡ 1, …), so a number equals the sum of its digits mod 9.
3Hint 3Explore hintHide hint
The single-digit result is therefore n mod 9 — except multiples of 9 map to 9, not 0, and n = 0 maps to 0. The clean closed form is `1 + (n − 1) % 9` for n > 0.
A · Core idea
The repeated digit sum (keep summing until one digit remains) is called the digital root, and it equals n reduced modulo 9 — with two careful adjustments. So the entire nested process collapses into a single formula evaluated in constant time.
Why the digit sum is congruent to n mod 9. Write n in base 10: n = d_k·10^k + … + d_1·10 + d_0. Since 10 ≡ 1 (mod 9), every power 10^i ≡ 1 (mod 9), so n ≡ d_k + … + d_1 + d_0 (mod 9) — the number and its digit sum leave the same remainder when divided by 9. This is the old 'casting out nines' trick. Repeating the digit sum never changes that remainder, so the final single digit is just n mod 9.
Why plain `n % 9` is wrong. The catch is the boundary. For a positive multiple of 9 (like 18 or 99), n % 9 == 0, but the digital root is 9, not 0. And n = 0 genuinely has digital root 0. The expression 1 + (n − 1) % 9 threads both needles: for n = 9 it gives 1 + 8 % 9 = 9; for n = 18 it gives 1 + 17 % 9 = 9; for n = 10 it gives 1 + 9 % 9 = 1. You still special-case n = 0 because (0 − 1) % 9 is not what we want.
Why this is the standout answer. Most candidates write a while n >= 10 loop that calls the digit-sum repeatedly — correct, but O(log n) per pass and visibly more code. Producing the closed form and explaining the mod-9 reason signals genuine number-theory fluency rather than pattern matching.
When to still loop. If the interviewer wants to see the intermediate sums (e.g. for a teaching demo), or the base isn't 10, the loop is the safer, more transparent choice.
B · Visual dry run
Interactive dry run
Select a frame to connect the decision with its visual state.
n = 38Interactive diagram
Why repeated summing equals n mod 9
guardEach power of 10 is congruent to 1 mod 9, so the digit sum keeps the same remainder.
2C · Code with teaching comments
D · Why it works and complexityO(1) timeO(1) spaceOpen the invariant and proofExplore the proofHide the proof
Repeated digit summing is a mod-9 operation in disguise. Recognizing that an apparently iterative process has an algebraic closed form — and guarding the two boundary cases — is the whole trick.
ComplexityO(1) time, O(1) space — No loop at all — a constant number of arithmetic operations regardless of how many digits n has.
E · Edge cases and pitfalls6n = 0 — Special-cased to return 0; the formula would otherwise mishandle (0 − 1) % 9.Explore edge casesHide edge cases
Edge cases handled
n = 0Special-cased to return 0; the formula would otherwise mishandle (0 − 1) % 9.n = 91 + (9 − 1) % 9 = 1 + 8 = 9 — correctly returns 9, not 0.n = 181 + (18 − 1) % 9 = 1 + 8 = 9 — the multiple-of-9 case the naive n % 9 gets wrong.
Pitfalls
- Writing `n % 9` directly — returns 0 for multiples of 9 instead of 9.
- Applying the formula to n = 0 without the guard.
- Forgetting abs(n) so a negative input feeds the formula a negative remainder.
Practice
Try the solution yourself
Edit the optimal implementation, test another input, and observe the result.
Editable code previewpublic int digitalRoot(int n) { n = Math.abs(n); if (n == 0) { return 0; }Explore the playgroundClose the playground
Avoid mistakes
Recognize the interview traps
Understand why common attempts fail before reviewing the corrected implementation.
1Using n % 9 for the digital root
For positive multiples of 9 the remainder is 0, but the true digital root is 9. The shifted formula fixes the boundary.
Explore the code comparisonHide the code comparison
Using n % 9 for the digital root
For positive multiples of 9 the remainder is 0, but the true digital root is 9. The shifted formula fixes the boundary.
Don't write this
public int digitalRoot(int n) {
return n % 9; // 18 % 9 = 0, but dr(18) = 9
}Write this instead
public int digitalRoot(int n) {
if (n == 0) return 0;
return 1 + (n - 1) % 9;
}2Infinite loop from a missing shift
If you read n % 10 but never divide n by 10, n stays the same and the while condition never becomes false.
Explore the code comparisonHide the code comparison
Infinite loop from a missing shift
If you read n % 10 but never divide n by 10, n stays the same and the while condition never becomes false.
Don't write this
total = 0
while n > 0:
total += n % 10
# forgot n //= 10 — loops forever
return totalWrite this instead
total = 0
while n > 0:
total += n % 10
n //= 10
return total3Signed remainder on negative input
Java's `-123 % 10` is -3, so summing without abs() yields a smaller (or negative) total than intended.
Explore the code comparisonHide the code comparison
Signed remainder on negative input
Java's `-123 % 10` is -3, so summing without abs() yields a smaller (or negative) total than intended.
Don't write this
int sum = 0;
while (n != 0) {
sum += n % 10; // negative digits for negative n
n /= 10;
}
return sum;Write this instead
n = Math.abs(n);
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;Revise
Carry the pattern into the interview
Pattern to remember
Digit extraction via %10 // 10, plus the mod-9 digital-root shortcut
Code pattern to memorize
# one-pass digit sum
s = 0
while n > 0:
s += n % 10
n //= 10
# digital root in O(1)
dr = 0 if n == 0 else 1 + (n - 1) % 9Rules to remember
- 1
n % 10peels off the last digit;n //= 10drops it. Forgetting the//= 10is an infinite loop. - 2The digital root is not
n % 9. That formula returns0for multiples of 9 (like 18 → 0) when the true root is9. Use1 + (n − 1) % 9. - 3Handle
n = 0separately: its digit sum and digital root are both0, but1 + (n − 1) % 9would give the wrong answer. - 4Take
abs(n)first if negatives are allowed —−123 % 10differs by language (Java gives−3, Python gives7). - 5Be clear which problem you're solving: a single pass (sum the digits once) versus repeated summing down to one digit (the digital root).
Use this pattern when
- You need to collapse a number to a single-digit fingerprint (checksums, Harshad/Niven checks)
- Validating IDs/card numbers where a digit-derived check value is required
- Any time you'd otherwise convert to a string just to add digits — the arithmetic version is cleaner
- The repeated-sum / digital-root framing where the O(1) congruence is the standout answer
Choose another pattern when
- You need the digits in order or by position → string/array indexing is clearer than %10 //10
- You need digits of an arbitrary-precision BigInteger → string traversal avoids slow big-number divides
- The number is given as a string already → just iterate characters
Interview takeaway
The loop is trivial; the interview edge is the digital-root insight — that repeatedly summing digits is congruent to n mod 9, so the whole repeated process collapses to one O(1) formula once you guard 0 and multiples of 9.
Continue
Transfer the pattern to another problem
Use a direct variation or pattern sibling to prove the idea is reusable.
Transferable patternDigit extraction with %10 // 10, elevated by the casting-out-nines insight. Recognize the repeated-digit-sum as a mod-9 operation, and you turn a nested loop into a constant-time formula — the same algebraic-shortcut instinct applies to divisibility and checksum problems.
Practice queueDirect variations and pattern siblings
Direct follow-ups
- Happy NumberRepeatedly sum the squares of digits and detect a cycle with a set or Floyd's algorithm.
- Add Digits (LeetCode 258)The classic digital-root problem — the O(1) congruence is exactly the optimal answer.
- Armstrong NumberSame digit extraction, but you raise each digit to the power of the digit count and compare to n.