The Fake Geek's blog: Self Excluding Product
Read full article from The Fake Geek's blog: Self Excluding Product
* Implement a method which takes an integer array and returns an integer array (of equal size) in
* which each element is the product of every number in the input array with the exception of the
* number at that index.
*
* Example:
* [3, 1, 4, 2] => [8, 24, 6, 12]
*/
public int[] selfExcludingProduct(int[] input) {
// implementation...
}
public
int
[] selfExcludingProduct (
int
[] input) {
if
(input ==
null
)
throw
new
NullPointerException (
"Null input array!"
);
int
[] productArray =
new
int
[input.length];
if
(input.length == 0)
return
productArray;
int
product = 1;
int
numOfZeros = 0;
for
(
int
i = 0; i < input.length; i++) {
if
(input[i] != 0)
product *= input[i];
else
numOfZeros++;
if
(numOfZeros >= 2) {
return
productArray;
}
}
for
(
int
i = 0; i < input.length; i++) {
if
(numOfZeros == 0) {
productArray[i] = product / input[i];
}
else
{
if
(input[i] == 0)
productArray[i] = product;
else
productArray[i] = 0;
}
}
return
productArray;
}