繁体   English   中英

计算使用递归的数组中的负数?

[英]count the number of negatives in an array using recursion?

我已经编写了一个对数组中的负数进行计数的代码,现在需要使用递归技术编写相同的代码。 我是递归的新手,所以不确定此代码是否正确。

public int countNeg (int[ ] nums, int n)
{
    int neg = 0;
    for (int index = 0; index < n; index ++)
        if (nums[index] < 0)
            neg++;
    return neg;
}

对于递归代码,这就是我所做的:

public int countNeg (int[ ] nums, int n)
{
     if (n < 0)
         return 0;
     else {
         int neg = countNeg (nums, n-1);
         if (nums[n-1] < 0)
             return neg + 1;
         else
             return neg;
      }
}

n是索引的参数。 您可以使用以下方法:

int numberOfNegativeNumbers = countNeg(nums, 0);

方法:

public int countNeg (int[ ] nums, int n) {
  if(n >= nums.length)
    return 0;
  else
    return ((mums[n] < 0) ? 1 : 0) + countNeg(nums, n+1);
}

@Bilghen的答案已提供所需的解决方案。

但是,我将提供使用尾递归技术的解决方案。

public int countNeg (int[ ] nums, int index) {
  return countNegTailRecur(nums, index, 0);
}

public int countNegTailRecur (int[ ] nums, int index, int total) {
  if(index >= nums.length)
    return total;
  else
    return countNeg(nums, index+1, nums[index] < 0 ? total + 1 : total);
}

这样称呼它-

int numberOfNegativeNumbers = countNeg(nums, 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM