这是我用来学习的旧测试。 我需要编写一个递归方法,从位置0和右侧返回int []上的零个数。 给定int numberOfZeroes(int [] a,int right);
答案 0 :(得分:1)
int numberOfZeroes(int[] a, int right) {
if (right == 0) return 0;
return numberOfZeros(a, right-1) + a[right] == 0 ? 0 : 1;
}
使用多个零(in,a.length)来获取整个数组中的零个数。
答案 1 :(得分:1)
这假定为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
}
}