我有一个任务(家庭作业)来计算可以除以2的数组中元素的数量,我需要以递归的方式进行操作以提高性能.问题是我的计数器不保留该值并且仅返回1而不是示例中可以除以2的元素数,它应该返回7
您可以查看尝试记住的代码,我需要它以递归的方式而不是使用for循环的常规方式进行操作,这更容易…
public class Sample1{
public static void main(String[] args) {
int [] array = {2,4,6,8,14,12,14};
System.out.println(what(array));
}
/**
*
* @param a an array of of numbers
* @return the number of numbers that can divided by 2
*/
public static int what (int []a){
return countingPairNumberes (a,a.length - 1,0);
}
/**
*
* @param a an array of of numbers
* @param lo the begining of the array
* @param hi the end of the array
* @return the number of numbers that can divided by 2
*/
private static int countingPairNumberes (int [] a,int lo,int hi,int sum)
{
int counter = sum;
if (lo <= hi) {
if(a[lo] % 2 == 0)
counter++;
countingPairNumberes (a,lo+1,hi,counter);
}
return counter;
}
}
我的预期结果是该计数器将是7,这就是我要在屏幕上打印的结果,但是我却得到了值1.
最佳答案
您无需将sum作为参数传递给递归方法.而且您不应该忽略递归调用的结果.
给定数组中的偶数计数是删除第一个元素后获得的子数组的偶数计数,如果删除的元素是偶数,则可以选择加1.
/**
*
* @param a an array of of numbers
* @return the number of numbers that can divided by 2
*/
public static int what (int []a){
return countingPairNumberes (a,a.length - 1);
}
/**
*
* @param a an array of of numbers
* @param lo the begining of the array
* @param hi the end of the array
* @return the number of numbers that can divided by 2
*/
private static int countingPairNumberes (int [] a,int hi)
{
if (lo <= hi) {
int counter = countingPairNumberes (a,hi);
if(a[lo] % 2 == 0)
counter++;
return counter;
} else {
return 0;
}
}