2015-11-06 102 views
0

我需要编写一个递归方法来计算数组中奇数整数的数量。计算数组中奇数整数数的递归方法

这里是我到目前为止的代码:

public static int countOdd(int[] numbers, int startIndex, int endIndex) { 
    if (startIndex == endIndex) { 
     if (numbers[startIndex] % 2 != 0) { 
      return 1; 
     } else { 
      return 0; 
     } 
    } else { 
     return countOdd(numbers, startIndex, endIndex - 1); 
    } 
} 
+1

什么是你的代码中的问题? – RealSkeptic

+0

你可能不需要startIndex被传递,并且你不需要外部的else在内部你可以在返回语句中做递归调用 – dharam

+0

它保持retu不管是什么@RealSkeptic – Suds2

回答

1

你的递归行不正确:

return countOdd(numbers, startIndex, endIndex - 1); 

你已经失去了endIndex的是奇数。这将有助于:

return countOdd(numbers, startIndex, endIndex - 1) + 
    countOdd(numbers, endIndex, endIndex); 

而且我不知道,如果你调用它的权利,我假定这将是:

countOdd(numbers, 0, numbers.length-1); 

解释器:为了了解如何执行它,你需要打破这个问题。如果我想在阵列递归计数奇数:

[a, b, c, d, e, f, g, .... z] 

上述基本的代码执行此:

countOdd([a, b, c, d, e, f, g, ...y]) + countOdd([z]) 

通知第二个操作数将返回0或1,因为子集的大小为1的。第一个操作数基本上是长度1更小。递归继续:

countOdd([a, b, c, d.... x]) + countOdd([y]) + countOdd([z]) 
... 
countOdd([a]) + countOdd([b]) + countOdd([c]) + ... countOdd([z]) 

而且一旦它们都是大小为1的子集,它就可以计算它。

0 + 1 + 0 + 1 + 1 .. 

并返回单个计数的奇数结果。

附加说明:注意,递归可以做不同的,但还是拿出了同样的结果(例如:

return countOdd(numbers, startIndex, startIndex) + 
    countOdd(numbers, startIndex + 1, endIndex); 
+0

谢谢你的作品。我仍然不明白,但 – Suds2

+0

哪一部分你不明白? – ergonaut

+0

递归部分?它甚至返回什么? – Suds2

0

能不能请你:

<your main class>{ 
    //global variables 
    int index = 0; 
    int[] array = {1,2,3,4,5}; 
    int counter = 0; 
    int totalOfOddNumbers = countOddIntegers(index); 

    System.out.println(totalOfOddNumbers); 
} 

private int countOddIntegers(int i){ 
    if (array[i] == 1) || (array[i]%2 != 0) counter ++; 
    if (i != array.length - 1) return countOddIntegers(i+1); 
    else return counter; 
}