-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProductOfNumbers_WithoutDivision.java
72 lines (60 loc) · 1.73 KB
/
ProductOfNumbers_WithoutDivision.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// without division
public class ProductOfNumbers_WithoutDivision {
public static void main(String[] args)
{
int[] array = new int[]{3,2,1};
int[] newArray = productOfNumbers(array);
for(int i = 0; i < newArray.length; i++)
{
System.out.print(newArray[i] + " ");
}
}
public static int[] productOfNumbers(int[] inputArray)
{
int length = inputArray.length;
int[] arr1 = new int[length];
int[] arr2 = new int[length];
int[] result = new int[length];
// prefix multiplication of inputArray from left to right
for(int i = 0; i < length; i++)
{
if(i != 0)
{
arr1[i] = inputArray[i] * arr1[i-1];
}
else
{
arr1[i] = inputArray[i];
}
}
// prefix multiplication of inputArray from right to left
for(int i = length-1; i >= 0; i--)
{
if(i != length-1)
{
arr2[i] = inputArray[i] * arr2[i+1];
}
else
{
arr2[i] = inputArray[i];
}
}
// populate result based on arr2[i+1] * arr1[i-1] provided they are within bounds
for(int i = 0; i < length; i++)
{
if(i-1 < 0) // out of bounds for arr1 - substitute with 1
{
result[i] = arr2[i+1] * 1;
}
else if(i+1 >= length) // out of bounds for arr2 - substitute with 1
{
result[i] = 1 * arr1[i-1];
}
else
{
result[i] = arr2[i+1] * arr1[i-1];
}
}
return result;
}
}