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

前端之家收集整理的这篇文章主要介绍了java-计算递归方法中可以除以2的元素 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个任务(家庭作业)来计算可以除以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;
    }

}
原文链接:https://www.f2er.com/java/532936.html

猜你在找的Java相关文章