计算可以在递归方法中除以2的元素



我有一个任务(家庭作业(,以计算数组中可以除以2的元素的数量,我需要以递归方式进行操作,以提高性能。问题是我的计数器不保留值并仅返回1,而不是可以除以2的元素数量,在我的示例中应该返回7

您可以查看尝试的代码,请记住我需要以递归方式进行操作,而不是常规方式使用循环,这更容易...

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, 0, 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, 0, 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 lo, int hi)
{
    if (lo <= hi) {
        int counter = countingPairNumberes (a, lo+1, hi);
        if(a[lo] % 2 == 0)
            counter++;
        return counter;
    } else {
        return 0;
    }
}

最新更新