Sum of Digits
Java coding interview problem for Basic Number Programs: Sum of Digits.
Finding the Sum of Digits is one of the most common Java coding interview questions. It helps interviewers evaluate your understanding of loops, arithmetic operators, digit extraction, and problem-solving skills.
This question is frequently asked in Java, C, C++, and programming interviews because it forms the foundation for many other number-based problems.
What is the Sum of Digits?
The Sum of Digits means adding every digit of a given number.
For example,
Input
1234
Calculation
1 + 2 + 3 + 4 = 10
Output
10
Example 1
Input
5678
Calculation
5 + 6 + 7 + 8
=
26
Output
26
Example 2
Input
1005
Calculation
1 + 0 + 0 + 5
=
6
Output
6
Example 3
Input
9
Calculation
9
Output
9
Real Interview Question
Write a Java program to find the sum of digits of a given number without converting it into a String.
Understanding the Logic
The idea is simple.
- Extract the last digit.
- Add it to the sum.
- Remove the last digit.
- Repeat until the number becomes zero.
Example
456
Extract digits
6
↓
5
↓
4
Sum
6
↓
11
↓
15
Final Answer
15
Brute Force Approach
The easiest solution is
- Extract the last digit using
% - Add it to the running sum
- Remove the last digit using
/ - Continue until the number becomes zero
Algorithm
Step 1
Read the input number.
Step 2
Initialize
sum = 0;
Step 3
Extract the last digit.
digit = number % 10;
Step 4
Add the digit to the sum.
sum = sum + digit;
Step 5
Remove the last digit.
number = number / 10;
Step 6
Repeat until
number = 0
Step 7
Print the final sum.
Dry Run
Input
1234
| Iteration | Number | Digit | Sum |
|---|---|---|---|
| 1 | 1234 | 4 | 4 |
| 2 | 123 | 3 | 7 |
| 3 | 12 | 2 | 9 |
| 4 | 1 | 1 | 10 |
Output
10
Another Dry Run
Input
56789
| Iteration | Number | Digit | Sum |
|---|---|---|---|
| 1 | 56789 | 9 | 9 |
| 2 | 5678 | 8 | 17 |
| 3 | 567 | 7 | 24 |
| 4 | 56 | 6 | 30 |
| 5 | 5 | 5 | 35 |
Output
35
Approach 1 — Using Arithmetic Operators
This is the most common interview solution.
Complete Java Program
public class SumOfDigits {
public static void main(String[] args) {
int number = 12345;
int sum = 0;
while (number != 0) {
int digit = number % 10;
sum = sum + digit;
number = number / 10;
}
System.out.println("Sum of Digits = " + sum);
}
}
Output
Sum of Digits = 15
Step-by-Step Code Explanation
Step 1
Declare the input number.
int number = 12345;
Current number
12345
Step 2
Initialize the sum.
int sum = 0;
Initially
Sum = 0
Step 3
Extract the last digit.
int digit = number % 10;
Example
12345 % 10 = 5
The modulus (%) operator always returns the last digit.
Step 4
Add the digit to the sum.
sum = sum + digit;
Initially
0 + 5 = 5
Next iteration
5 + 4 = 9
Next
9 + 3 = 12
Eventually
15
Step 5
Remove the last digit.
number = number / 10;
Example
12345
↓
1234
↓
123
↓
12
↓
1
↓
0
Step 6
Repeat the process.
The loop continues until
number == 0
Each iteration processes exactly one digit.
Step 7
Display the result.
System.out.println("Sum of Digits = " + sum);
Output
Sum of Digits = 15
Why Does This Work?
The algorithm processes one digit at a time.
Each iteration performs two important operations:
- Extracts the last digit using
%. - Removes the last digit using
/.
For
12345
The digits are processed as
5
↓
4
↓
3
↓
2
↓
1
Running sum
5
↓
9
↓
12
↓
14
↓
15
Therefore,
Sum of Digits = 15
Advantages of This Approach
- Simple and easy to understand.
- No extra data structures are required.
- Uses only arithmetic operators.
- Works efficiently for positive integers.
- Preferred solution in Java coding interviews.
- Uses constant extra memory.
Drawbacks
This solution works perfectly for most interview questions, but interviewers often ask follow-up questions such as:
- Can you solve it using a reusable method?
- Can you solve it recursively?
- Can you solve it using String conversion?
- What if the number is negative?
- Which approach is the most efficient?
In the next part, we'll cover:
- Reusable method approach
- Recursive solution
- String-based solution
- Time and space complexity
- Comparison of all approaches
- Common interview mistakes
- Frequently asked interview questions
- Related coding problems
- Key takeaways
- Interview tips
Approach 2 — Using a Reusable Method
Instead of writing the logic inside the main() method, we can create a reusable method.
This approach improves
- Code reusability
- Readability
- Unit testing
- Maintainability
Java Program
public class SumOfDigitsMethod {
static int findSum(int number) {
int sum = 0;
while (number != 0) {
int digit = number % 10;
sum += digit;
number = number / 10;
}
return sum;
}
public static void main(String[] args) {
int number = 98765;
int result = findSum(number);
System.out.println("Sum of Digits = " + result);
}
}
Output
Sum of Digits = 35
Approach 3 — Recursive Solution
Recursion is another elegant solution frequently asked during interviews.
Instead of using a loop,
the function repeatedly calls itself until the number becomes zero.
Logic
1234
↓
4 + Sum(123)
↓
4 + 3 + Sum(12)
↓
4 + 3 + 2 + Sum(1)
↓
4 + 3 + 2 + 1
↓
10
Java Program
public class SumOfDigitsRecursive {
static int findSum(int number) {
if (number == 0) {
return 0;
}
return number % 10 + findSum(number / 10);
}
public static void main(String[] args) {
int number = 1234;
System.out.println(findSum(number));
}
}
Output
10
Approach 4 — Using String Conversion
Although interviewers usually expect an arithmetic solution,
Java also allows solving this problem using String operations.
Java Program
public class SumUsingString {
public static void main(String[] args) {
String number = "12345";
int sum = 0;
for (char digit : number.toCharArray()) {
sum += digit - '0';
}
System.out.println("Sum of Digits = " + sum);
}
}
Output
Sum of Digits = 15
Time Complexity
Arithmetic Solution
| Operation | Complexity |
|---|---|
| Time | O(log₁₀ n) |
| Space | O(1) |
Recursive Solution
| Operation | Complexity |
|---|---|
| Time | O(log₁₀ n) |
| Space | O(log₁₀ n) |
The extra space is used by the recursion call stack.
String Solution
| Operation | Complexity |
|---|---|
| Time | O(log₁₀ n) |
| Space | O(log₁₀ n) |
Comparison of All Approaches
| Approach | Time | Space | Recommended |
|---|---|---|---|
| Arithmetic Operators | O(log n) | O(1) | ✅ Best |
| Reusable Method | O(log n) | O(1) | Reusable |
| Recursion | O(log n) | O(log n) | Good for Learning |
| String Conversion | O(log n) | O(log n) | Easy but Less Preferred |
Common Mistakes
Mistake 1
Using
number / 10
before extracting the digit.
Wrong
number = number / 10;
digit = number % 10;
Correct
digit = number % 10;
number = number / 10;
Mistake 2
Forgetting to initialize
sum = 0;
This produces incorrect results.
Mistake 3
Using
number % 10
without removing the processed digit.
Always write
number = number / 10;
Otherwise,
the loop never terminates.
Mistake 4
Ignoring negative numbers.
Example
-123
A common approach is
number = Math.abs(number);
before processing the digits.
Mistake 5
Using String conversion when the interviewer explicitly asks
"Solve it without converting the number into a String."
In such cases,
always use arithmetic operators.
Interview Follow-up Questions
Q1. Find the sum of digits without using String.
Q2. Solve the problem recursively.
Q3. Find the product of digits.
Q4. Find the average of digits.
Q5. Find the largest digit.
Q6. Find the smallest digit.
Q7. Find the sum of even digits.
Q8. Find the sum of odd digits.
Q9. Find the digital root of a number.
Q10. Reverse a number and then find its digit sum.
Related Coding Problems
- Count Digits
- Reverse Integer
- Product of Digits
- Largest Digit
- Smallest Digit
- Armstrong Number
- Palindrome Number
- Reverse String
Key Takeaways
- Extract each digit using the modulus (
%) operator. - Remove the processed digit using integer division (
/). - The arithmetic approach is the most efficient and interview-friendly solution.
- A recursive solution is elegant but consumes additional stack space.
- String conversion is simple but is usually not preferred when arithmetic manipulation is expected.
- The arithmetic solution runs in O(log n) time and uses O(1) extra space.
Interview Tip
If an interviewer asks:
"Write a Java program to find the sum of digits of a number."
Begin with the arithmetic solution using % and /, since it is the most efficient and demonstrates your understanding of number manipulation. After implementing it, mention alternative approaches such as recursion and String conversion, and explain their trade-offs in terms of readability, space usage, and interview expectations. This shows both coding proficiency and a good understanding of algorithmic design.