How to Find Sum of Digits in Java
The Challenge
Calculate the sum of all digits in a number - e.g., 123 1+2+3 = 6
Solution
public class Main {
public static void main(String[] args) {
int number = 12345;
int sum = 0;
while (number > 0) {
int digit = number % 10; // Get last digit
sum += digit; // Add to sum
number /= 10; // Remove last digit
}
System.out.println("Sum of digits: " + sum);
// Output: Sum of digits: 15 (1+2+3+4+5)
}
}Step-by-Step Explanation
For number 123:
- Iteration 1: digit = 3, sum = 3, number = 12
- Iteration 2: digit = 2, sum = 5, number = 1
- Iteration 3: digit = 1, sum = 6, number = 0
- Result: Sum = 6
Using Recursion
public static int sumOfDigits(int num) {
if (num == 0) {
return 0;
}
return (num % 10) + sumOfDigits(num / 10);
}
// Usage
System.out.println(sumOfDigits(12345)); // 15Did You Know?
The sum of digits is used in the "digital root" concept - keep summing until you get a single digit! For 12345: 15 6 (digital root)
Pro Tip
This technique is used in checksum algorithms to verify data integrity, like credit card validation (Luhn algorithm)!
Real-World Use Cases
- Credit cards: Luhn algorithm for validation
- ISBN numbers: Book identification verification
- Numerology: Calculate life path numbers
- Data validation: Checksum calculations
›Short versionOpen if you only have a minute.
- Take n % 10, add it, then set n = n / 10, until n is 0.
- Forgetting the division spins forever on any non-zero n.
- Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE. The positive value does not fit.
- Leading zeros exist only in a string. An int 007 is just 7.
Sum of digits
Add every digit in a number by extracting one digit at a time.
Working approach
- Decide whether a leading minus is ignored. If it is, work from a long copy.
- Accumulate in a separate variable. Do not reuse the input as the sum.
- Stop when the remaining value is 0. The sum of the digits of 0 is 0.
Walk the sample
- Input 472
- Add 2, remaining 47
- Add 4, remaining 4
- Add 4, sum is 13
The trap
Math.abs on an int cannot represent the negation of Integer.MIN_VALUE, so a "make it positive first" step leaves the number negative and the digit loop does not run.
static int digitSum(int n) {
long value = Math.abs((long) n); // widen first; abs(Integer.MIN_VALUE) does not fit in int
int sum = 0;
while (value > 0) {
sum += (int) (value % 10);
value /= 10;
}
return sum;
}Why does Math.abs(Integer.MIN_VALUE) stay negative?
The mathematical result is 2147483648, one past Integer.MAX_VALUE. The int method returns the original bit pattern.
Cast to long before the absolute value. A digit loop conditioned on n > 0 then sees a positive value.
Time O(d), space O(1), where d is the digit count.
Easy to get wrong
- Updating the sum and not the remaining number.
- Calling Math.abs on the int before widening it.