Find Sum of Digits in Java
What you’ll learn
- How to extract digits using
% 10and/ 10. - The accumulator pattern:
sum += digit. - How to handle negatives and zero safely.
Overview
To find the sum of digits, repeatedly take the last digit and add it to a running total. For 12345, the result is 15.
Two Java examples
Fixed number and user-input number versions.
Live preview
Type values like 12345 or -802.
Next step
Repeated digit sums lead to digital root.
Live preview
Enter an integer and see its digits and their sum.
Algorithm
Goal: compute sum of all decimal digits of n.
Normalize sign
Take absolute value first.
Extract digits
Use n % 10 and n / 10 in a loop.
Accumulate
Add each digit to running sum.
📜 Pseudocode
function sumOfDigits(n):
n = abs(n)
if n == 0:
return 0
sum = 0
while n > 0:
sum = sum + (n mod 10)
n = floor(n / 10)
return sumSum of digits (fixed number)
This example calculates sum of digits for 12345.
public class Main {
static int sumOfDigits(int n) {
n = Math.abs(n);
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
int number = 12345;
System.out.println("Sum of digits of " + number + " is: " + sumOfDigits(number));
}
}Sum of digits (user input)
This version reads an integer and prints its digit sum.
import java.util.Scanner;
public class Main {
static int sumOfDigits(int n) {
n = Math.abs(n);
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
if (!sc.hasNextInt()) {
System.out.println("Invalid input.");
return;
}
int number = sc.nextInt();
System.out.println("Sum of digits: " + sumOfDigits(number));
}
}Optimization notes
Use string conversion for readability, or arithmetic loop for interview-style constant space.
❓ FAQ
🔄 Input / output examples
| Input | Digit sum |
|---|---|
12345 | 15 |
0 | 0 |
Edge cases and pitfalls
Common mistakes are around zero, sign handling, and absolute-value edge cases.
Return zero
When input is zero, digit sum should be zero.
Ignore sign
Use absolute value before extracting digits.
Advanced overflow case
For extreme negative int limits, use a wider type if needed.
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
| Sum digits of one number | O(d) (d = number of digits) | O(1) |
Summary
- Core loop:
sum += n % 10, thenn /= 10. - Sign handling: use absolute value for negative numbers.
- Complexity: linear in number of digits.
Repeatedly summing digits until one digit remains is called finding the digital root.
9 people found this page helpful
