如何使用递归方法找出数组中的奇数整数?

use*_*607 0 java arrays recursion

我正在尝试编写一种方法,查找在第一个位置和最后一个位置之间有多少个奇数.该方法接受一个数组,然后接受两个ints作为低位和高位.该方法需要递归地进行.这是我到目前为止所拥有的.这是方法调用和int数组.我得到1的输出,但答案应该是2.

int array [] = {5, 2, 5, 6, 3, 1};
int n = countOddsInRange(array, 1, 4)

public static int countOddsInRange(int [] a, int first, int last)
{
    int count = 0;
    if(first <= last)
    {
        countOddsInRange(a, a[first + 1], a[last]);
        if(a[first] % 2 == 0)
        {
            count++;
        }
    }
    return count;   
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 5

您的代码中有一些错误:

  1. 你算数偶数,不奇怪.把你的病情改为if(a[first] % 2 != 0)
  2. 递归调用应该获取数组的索引,而不是这些位置中的值.
  3. 您应该将递归调用的结果添加到total: count+=countOddsInRange(a, first + 1, last)

总结一下:

public static int countOddsInRange(int [] a, int first, int last)
{
    int count = 0;
    if(first <= last)
    {
        count+=countOddsInRange(a, first + 1, last);
        if(a[first] % 2 != 0)
        {
            count++;
        }
    }
    return count;   
}
Run Code Online (Sandbox Code Playgroud)