返回零个数的递归方法

发布于 2024-10-20 11:45:47 字数 100 浏览 2 评论 0原文

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

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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千と千尋 2024-10-27 11:45:47

这假设 right < a.长度

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
  }
}

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
  }
}
莳間冲淡了誓言ζ 2024-10-27 11:45:47
int numberOfZeroes(int[] a, int right) {
     if (right == 0) return 0;
     return numberOfZeros(a, right-1) + a[right] == 0 ? 0 : 1;
} 

执行 numberOfZeros(a, a.length) 来获取整个数组中零的数量。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文