Sum of Digits in Java
Problem
The sum of a number's digits is found by peeling off one digit at a time and adding each one into a running total.
Given a number, find the sum of its individual digits.
Java Program
public class SumOfDigits {
public static void main(String[] args) {
int n = 12345;
int sum = 0;
while (n > 0) {
sum += n % 10; // add the last digit into the running total
n /= 10;
}
System.out.println("Sum of digits: " + sum);
}
}Output
Core Logic
Repeatedly pulling off the last digit with the modulo operator, and adding it into a running total, sums every digit without ever needing to know the number's length up front.
- 1
n % 10extracts the current last digit ofn. - 2That digit is added into
sum. - 3
n /= 10removes the digit just processed, shifting the next one into place. - 4The loop continues until
nreaches0, meaning every digit has been added.
12345, the digits 5, 4, 3, 2, 1 are peeled off one at a time and summed to 15.Key Point: The order digits are visited in — last to first — doesn't matter for a sum, since addition doesn't care about order.
Why: Each loop iteration strips exactly one digit off n, so the number of iterations equals n's digit count d, with only a running total kept.
Key Concepts
Approach 2: Java 8
public class SumOfDigitsStream {
public static void main(String[] args) {
int n = 12345;
// Converts each digit character back to its numeric value, then sums them
int sum = String.valueOf(n).chars().map(c -> c - '0').sum();
System.out.println("Sum of digits: " + sum);
}
}
Output
Core Logic
Treating the number as a string of digit characters lets a stream sum them directly, without any manual arithmetic loop.
- 1
String.valueOf(n)converts the number into its digit string. - 2
.chars()streams each character's underlying code point. - 3
.map(c -> c - '0')converts each character code back into its numeric digit value. - 4
.sum()reduces the stream of digits down to a single total.
12345, the stream converts each character to its digit and sums them to 15, the same result the loop finds.Key Point: The c - '0' trick works because digit characters are laid out consecutively in code order, so subtracting '0' gives the digit's numeric value directly.
Why: The stream still visits each of the d digit characters once, converting and summing them without collecting anything.