-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProductOfArrayExceptSelf.java
48 lines (39 loc) · 1.18 KB
/
ProductOfArrayExceptSelf.java
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
import java.util.Arrays;
class ProductOfArrayExceptSelf {
public int[] productExceptSelf(int[] nums) {
int numOfZeroes = 0;
int totalProduct = 1;
for (int i=0 ; i< nums.length; i++){
if (nums[i]==0){
numOfZeroes++;
continue;
}
totalProduct *= nums[i];
}
int []result = new int[nums.length];
if(numOfZeroes > 1){
for(int i=0 ; i< result.length; i++){
result[i] = 0;
}
return result;
}
if(numOfZeroes == 1){
for(int i=0 ; i< result.length; i++){
if(nums[i]==0){
result[i] = totalProduct;
continue;
}
result[i] = 0;
}
return result;
}
for(int i=0 ; i< result.length; i++){
result[i] = totalProduct / nums[i];
}
return result;
}
public static void main(String[] args) {
int []nums = {1,2,3,4};
System.out.println(Arrays.toString(new ProductOfArrayExceptSelf().productExceptSelf(nums)));
}
}