加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:30:09 所属栏目:Java 来源:网络整理
导读:我有一个任务(家庭作业)来计算可以除以2的数组中元素的数量,我需要以递归的方式进行操作以提高性能.问题是我的计数器不保留该值并且仅返回1而不是示例中可以除以2的元素数,它应该返回7 您可以查看尝试记住的代码,我需要它以递归的方式而不是使用for循环的常

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

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读