Category: Easy | Concepts used: Modulo, integer division, recursion
Problem Statement
Given an integer, find the sum of its individual digits.
Input : 1234 Output: 10 (1+2+3+4)
Input : 7 Output: 7 (single digit)
Examples (with edge scenarios)
| # | Input | Output | Why |
|---|---|---|---|
| 1 | 1234 | 10 | 1+2+3+4 |
| 2 | 7 | 7 | Single digit โ sum is itself |
| 3 | 0 | 0 | Zero has โone digit,โ which is 0 |
| 4 | -123 | 6 (or -6?) | Negative numbers โ clarify: do we sum digit magnitudes only, or keep the sign? Usually digit sums are taken as positive |
| 5 | 1000 | 1 | Trailing zeros contribute nothing to the sum |
Common Fresher Mistake
Mistake What happens Fix Not handling negative numbers %10on a negative number gives a negative digit, throwing off the sumTake Math.abs(n)first, or work with the negation, before extracting digitsConverting to a String and looping over characters, then treating each char as its ASCII value Off results, since '5'isnโt the integer5โ needCharacter.getNumericValue()or subtract'0'If going the String route, use Character.getNumericValue(ch)orch - '0'to convert correctly
Before You Code: Clarify the Contract
Before choosing an algorithm, confirm whether zero and negative values are allowed, how large the input can be, and what should happen when an arithmetic result exceeds the chosen Java type. The examples use the contract stated in this article, but an interview answer should say these assumptions aloud.
Analogy: Peeling an Onion
Imagine you have an onion (the number 1234), and you want to count the rings of each layer:
- The last digit (
4) is the outermost layer of the onion. - You peel it off using the modulo knife (
n % 10), add it to your bowl (sum += 4), and throw away the peeled skin. - The remaining onion is now smaller (
n / 10 = 123). - You repeat this process: peel the outer layer
3, then2, then1. - When thereโs nothing left of the onion (
n = 0), you stop. The bowl now contains the sum of all the peeled layer values!
Solution 1 โ Using Modulo and Integer Division (Recommended)
Intuition
n % 10 peels off the last digit of a number (e.g., 1234 % 10 = 4), and n / 10 (integer division) chops that last digit off, shrinking the number (1234 / 10 = 123). Repeating this โ peel off a digit, add it to a running sum, shrink the number โ eventually exhausts every digit, one at a time, from right to left.
public class SumOfDigits {
public static int sumOfDigits(int n) {
n = Math.abs(n); // handle negative numbers by working with magnitude
int sum = 0;
while (n > 0) {
int lastDigit = n % 10; // peel off the last digit
sum += lastDigit;
n = n / 10; // shrink the number
}
return sum;
}
public static void main(String[] args) {
System.out.println(sumOfDigits(1234)); // 10
System.out.println(sumOfDigits(7)); // 7
System.out.println(sumOfDigits(0)); // 0
System.out.println(sumOfDigits(-123)); // 6
}
}
Output:
10
7
0
6
Edge case note:
sumOfDigits(0)returns0correctly โ but only because the loop condition isn > 0. Ifnstarts at exactly0, the loop never runs, andsumstays at its initial value of0, which happens to be the right answer here.
Dry Run (n = 1234)
n=1234, sum=0
lastDigit=1234%10=4, sum=0+4=4, n=1234/10=123
lastDigit=123%10=3, sum=4+3=7, n=123/10=12
lastDigit=12%10=2, sum=7+2=9, n=12/10=1
lastDigit=1%10=1, sum=9+1=10, n=1/10=0
n=0 -> loop stops
Final sum = 10
Interviewerโs take
This is exactly the expected solution โ itโs the standard, efficient way to extract digits using pure arithmetic, without needing to convert to a String at all. Handling the negative-number edge case with Math.abs() up front is an important detail interviewers watch for.
Follow-up questions you might get:
- โWhat would happen if you forgot
Math.abs()?โ โ Forn = -123,n % 10in Java would give-3(negative remainder), and the loop conditionn > 0would actually never even trigger sincenstarts negative โ so the function would incorrectly return0for any negative input without the fix. - โCan you do this using recursion?โ โ leads to Solution 2.
Solution 2 โ Recursive Approach
Intuition
The problem has a natural recursive shape: โsum of digits of nโ = โlast digit of nโ + โsum of digits of the rest of n (with the last digit removed).โ Each recursive call handles one digit, until nothingโs left.
public class SumOfDigitsRecursive {
public static int sumOfDigits(int n) {
n = Math.abs(n);
if (n == 0) {
return 0; // base case: no digits left to add
}
return (n % 10) + sumOfDigits(n / 10); // last digit + sum of the rest
}
public static void main(String[] args) {
System.out.println(sumOfDigits(1234)); // 10
System.out.println(sumOfDigits(7)); // 7
}
}
Output:
10
7
Dry Run (n = 123)
sumOfDigits(123) = 3 + sumOfDigits(12)
sumOfDigits(12) = 2 + sumOfDigits(1)
sumOfDigits(1) = 1 + sumOfDigits(0)
sumOfDigits(0) = 0 (base case)
Unwinding: 1+0=1, 2+1=3, 3+3=6
Final: 6 (1+2+3 = 6)
Interviewerโs take
Equally valid โ same logic as the iterative version, just expressed recursively. Good to mention as an alternative; some interviewers specifically like to see if you can convert between iterative and recursive thinking for the same problem.
Follow-up questions you might get:
- โWhatโs the space complexity difference between iterative and recursive here?โ โ Iterative uses O(1) extra space; recursive uses O(d) space for the call stack, where
dis the number of digits (usually small, so not a big concern here, but worth mentioning).
๐ Visual Flowchart
graph TD
Start["Input Number n"] --> Absolute["n = Math.abs(n)"]
Absolute --> Init["Initialize sum = 0"]
Init --> Loop{"n > 0?"}
Loop -->|Yes| Mod["lastDigit = n % 10"]
Mod --> Add["sum += lastDigit"]
Add --> Div["n = n / 10"]
Div --> Loop
Loop -->|No| End["Return sum"]
Final Verdict โ Which Solution Should You Give?
- Both solutions are considered good. Solution 1 (iterative) is the more commonly expected default; Solution 2 (recursive) is a nice alternative to mention.
- The real differentiator is correctly handling negative numbers and zero โ call these out explicitly regardless of which version you write.
Quick Recap
| Approach | Time | Space | Interview Signal |
|---|---|---|---|
Iterative (% and /) | O(d) โ d = number of digits | O(1) | Preferred default |
| Recursive | O(d) | O(d) call stack | Good alternative |
- Author
- TechByteByByte Editorial Team
- Reviewed by
- TechByteByByte Admin
- Published
- Last reviewed