gpt4 book ai didi

java - 返回零个数的递归方法

转载 作者:行者123 更新时间:2023-11-30 05:05:33 25 4
gpt4 key购买 nike

这是我用来学习的一个旧测试。我需要编写一个递归方法,返回 int[] 上从位置 0 开始的零个数。给定 int numberOfZeroes(int[] a, int right);

最佳答案

这假设 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
}
}

关于java - 返回零个数的递归方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5214538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com