-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathP16_SumOfDigits.java
More file actions
46 lines (39 loc) · 1.26 KB
/
Copy pathP16_SumOfDigits.java
File metadata and controls
46 lines (39 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package programs;
/**
* ============================================================
* PROGRAM 16: Sum and Product of Digits
* ============================================================
* Problem: WAP to calculate the sum and product of all digits of an integer.
* - Input : 12345
* - Sum : 1 + 2 + 3 + 4 + 5 = 15
* - Prod : 1 * 2 * 3 * 4 * 5 = 120
* ============================================================
*/
public class P16_SumOfDigits {
public static void computeDigitStats(int n) {
int original = n;
n = Math.abs(n);
int sum = 0;
long product = (n == 0) ? 0 : 1;
if (n == 0) {
sum = 0;
product = 0;
} else {
while (n > 0) {
int digit = n % 10;
sum += digit;
product *= digit;
n /= 10;
}
}
System.out.printf("Number: %-6d -> Sum of Digits: %2d | Product of Digits: %d%n",
original, sum, product);
}
public static void main(String[] args) {
int[] testCases = {12345, 987, 405, 7, 0, -234};
System.out.println("=== SUM AND PRODUCT OF DIGITS ===");
for (int num : testCases) {
computeDigitStats(num);
}
}
}