尝试使用递归获取数组中偶数的总和

时间:2013-10-08 05:22:10

标签: java recursion

我想得到数组中偶数的总和:

 public static void main(String[] args) {
    int[] array = new int[4];
    array[0] = 1;
    array[1] = 2;
    array[2] = 2;
    array[3] = 4;

    System.out.println("Count even: " + countE(array, 0));      
 }   

public static int countE(int[] arr, int head) {
        if (arr.length == head) {
        return -1;
        } else if (arr[head] % 2 == 0) {              

            return 1 + countE(arr, head + 1);
    } else {

        return 0 + countE(arr, head + 1);
    }
}

6 个答案:

答案 0 :(得分:0)

if (arr.length == head) {
        return -1;

给你问题兄弟...你从最后的计数中减去1 ...尝试做

if (arr.length == head) {
        return 0;

答案 1 :(得分:0)

它可以通过递归完成,你添加错误的数字

        else if (arr[head]%2==0)
        {
            return arr[head] +  countHead(arr, head + 1);
        }

答案 2 :(得分:0)

它给你2,因为在最后一次递归中,它会扣除1 - 你的基本情况是错误的。改为0。

答案 3 :(得分:0)

我希望我不会为你揭示太多,它会带走学习的兴奋!

public static int countE(int[] array, int index) {
  int currentNumber = array[index];
  if(index == array.length) {
    // terminate it by returning a value that does not affect the sum (what integer is this?)
  } else {
    // check if even, if even, add the current number, else, add zero (both are recursive calls)
    if(isEven(currentNumber)) {
       return // your recursive call if even, currentNumber should be added
    } else {
       return // your recursive call if not, currentNumber should not be added
    }
  }
}

public static boolean isEven(int number) {
  return (number % 2 == 0) ? true : false;
}

答案 4 :(得分:0)

HLO。好友..试试这个

package com.smk.recursion;

public class SumOfEvenNoFromArray {
public static void main(String[] args) {

    int[] a = new int[5];
    a[0] = 2;
    a[1] = 5;
    a[2] = 4;
    a[3] = 4;
    a[4] = 4;

    System.out.println("Sum of Odd Numbers : "+sumEvenNoRecursion(a,(a.length-1)));

}

public static int sumEvenNoRecursion(int[] arr, int index){
    int sum;
    if(index == -1){
        return 0;
    }else if(arr[index]%2 == 0 ){           
        sum = arr[index] + sumEvenNoRecursion(arr, --index);            
    }else{
        sum =  sumEvenNoRecursion(arr, --index);            
    }
    return sum;


}
}

//输出

奇数之和:14

答案 5 :(得分:0)

您可以使用辅助函数进行递归。

public static int sumofEvens(int[] list){
    int sum = sumHelper(list, 0, 0);
    return sum;
}
private static int sumHelper(int[] list, int i, int sum){
    if(i < list.length){
        if(list[i] % 2 == 0){
            sum += list[i];
        }
        sum = sumHelper(list, i+1, sum);
    }
    return sum;
}