Reputation: 13
This is from an old test that I'm using to study. I need to write a recursive method that returns the number of zeroes on the int[] from position 0 and right. given int numberOfZeroes(int[] a, int right);
Upvotes: 1
Views: 2425
Reputation: 96934
This assumes right < a.length
int numberOfZeroes(int[] a, int right) {
if(right < 0) { // We've gone through all indices
return 0; // So we don't want to recurse anymore
} else if(a[right] == 0) { // The current index has a zero
return 1 + numberOfZeroes(a, right - 1); // Call the function, moving left one. Add one to the returned count since we found a zero
} else { // The current index does not have a zero
return numberOfZeroes(a, right - 1); // Call the function, moving left one. We don't add anything since we didn't find a zero
}
}
Upvotes: 1
Reputation: 21572
int numberOfZeroes(int[] a, int right) {
if (right == 0) return 0;
return numberOfZeros(a, right-1) + a[right] == 0 ? 0 : 1;
}
Do numberOfZeros(a, a.length) to get the number of zeros in the entire array.
Upvotes: 1