Product of Digits
Problem
Read an integer and print the product of its digits. Ignore the minus sign. If any digit is 0, the product is 0.
Constraints
- -10^18 <= n <= 10^18
Examples
Input
123
Output
6
Solutions
It is the same loop as the sum of digits, but the accumulator starts at 1 and we multiply. The input 0 needs its own check because the loop would not run and the product would stay 1.
/*
* Problem : Multiply all digits of a number.
* Input : One integer.
* Output : The product of the digits.
* Approach: Take digits one by one and multiply.
* Time : O(d)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
long number = Math.abs(new Scanner(System.in).nextLong());
// Step 1: Handle 0 first. Its only digit is 0, so the product is 0.
if (number == 0) {
System.out.println(0);
return;
}
// Step 2: Start the product with 1, because 1 does not change a product.
long product = 1;
// Step 3: Repeat until no digits are left.
while (number > 0) {
// Step 4: Take the last digit and multiply it into the product. Example: 123 % 10 = 3.
product = product * (number % 10);
// Step 5: Remove the last digit. Example: 123 / 10 = 12.
number = number / 10;
}
// Step 6: Print the product.
System.out.println(product);
}
}
Hints (3)
- Which operator gives the last digit of a number?
- Which operation removes the last digit?
- What value must a product start with?