Repository navigation
Expand file tree
/
Copy pathP1.java
More file actions
64 lines (51 loc) · 1.67 KB
/
Copy pathP1.java
File metadata and controls
64 lines (51 loc) · 1.67 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
public class P1 {
public static int[] productOfArrayExceptItself(int[] nums) {
if (nums == null || nums.length == 0) {
return new int[] {};
}
int product = 1;
int numZeroes = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
numZeroes += 1;
continue;
}
product *= nums[i];
}
int[] result = new int[nums.length];
if (numZeroes >= 2) {
return result;
}
for (int i = 0; i < result.length; i++) {
if (nums[i] == 0) {
result[i] = product;
continue;
}
result[i] = product / nums[i];
}
return result;
}
public static void main(String[] args) {
int[] input1 = new int[] { 1, 2, 3, 4 };
int[] input2 = new int[] { 0, 1, 2, 3 };
int[] input3 = new int[] { 0, 1, 2, 3, 0 };
int[] result1 = productOfArrayExceptItself(input1);
int[] result2 = productOfArrayExceptItself(input2);
int[] result3 = productOfArrayExceptItself(input3);
System.out.println("Input1's answer should be: [24, 12, 8, 6]");
for (int r : result1) {
System.out.print(r + " ");
}
System.out.println();
System.out.println("Input2's answer should be: [6, 6, 3, 2]");
for (int r : result2) {
System.out.print(r + " ");
}
System.out.println();
System.out.println("Input2's answer should be: [0, 0, 0, 0, 0]");
for (int r : result3) {
System.out.print(r + " ");
}
return;
}
}