Product of Digits in Java
Problem
The product of a number's digits is found by peeling off one digit at a time and multiplying each one into a running total.
Given a number, find the product of its individual digits.
Java Program
public class ProductOfDigits {
public static void main(String[] args) {
int n = 1234;
int product = 1; // multiplying by 1 leaves the first digit unaffected
while (n > 0) {
product *= n % 10;
n /= 10;
}
System.out.println("Product of digits: " + product);
}
}Output
Core Logic
Repeatedly pulling off the last digit with the modulo operator, and multiplying it into a running product, combines every digit without ever needing to know the number's length up front.
- 1
productstarts at1, since multiplying by1leaves the first digit unaffected. - 2
n % 10extracts the current last digit ofn. - 3That digit is multiplied into
product. - 4
n /= 10removes the digit just processed, and the loop continues untilnreaches0.
1234, the digits 4, 3, 2, 1 are peeled off one at a time and multiplied to 24.Key Point: Starting product at 1 — not 0 — is what matters here, since multiplying anything by 0 would zero out the whole result.
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 product kept.
Key Concepts
Approach 2: Java 8
public class ProductOfDigitsStream {
public static void main(String[] args) {
int n = 1234;
// Converts each digit character back to its numeric value, then folds them into a product
int product = String.valueOf(n).chars().map(c -> c - '0').reduce(1, (a, b) -> a * b);
System.out.println("Product of digits: " + product);
}
}
Output
Core Logic
Treating the number as a string of digit characters lets a stream fold them into a product 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
.reduce(1, (a, b) -> a * b)folds the stream of digits into a single product, starting from1.
1234, the stream converts each character to its digit and multiplies them to 24, the same result the loop finds.Key Point: The identity value passed to reduce() plays the same role as the loop's initial product = 1 — both need to be the multiplicative identity for the fold to start correctly.
Why: The stream still visits each of the d digit characters once, converting and folding them without collecting anything.