-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProductExceptSelf.java
More file actions
37 lines (31 loc) · 871 Bytes
/
ProductExceptSelf.java
File metadata and controls
37 lines (31 loc) · 871 Bytes
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
package Array;
public class ProductExceptSelf {
public static int[] productExceptSelf(int[] a) {
int prod = 1;
int flag = 0;
int n = a.length;
for (int num : a) {
if (num == 0) flag++;
else prod *= num;
}
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
if (flag > 1) {
arr[i] = 0;
} else if (flag == 0) {
arr[i] = (prod / a[i]);
} else if (flag == 1 && a[i] != 0) {
arr[i] = 0;
} else
arr[i] = prod;
}
return arr;
}
public static void main(String[] args) {
int[] a = {-1, 1, 0, -3, 3};
int[] exceptSelf = productExceptSelf(a);
for (int num : exceptSelf) {
System.out.print(num + " ");
}
}
}