[Algorithm] 두개의 배열에서 짝수의 합 구하기

최지영·2022년 9월 10일
0

✨ 주어진 두개의 배열에서 짝수의 합 구하기

사실 그냥 반복문으로 돌려서 구하는게 가장 간편하지만 굳이 괜히 재귀로 구현해보았다

public class Recursive {

private static Integer [] firstDataSet = {1,2,3,4};
    private static Integer [] secondDataSet = {11,12,13,14};
    public static void main(String[] args) {
        System.out.println(recursiveSum(0));

    }

   
    public static int recursiveEvenSum(Integer index){
        /**
         * 기저 사례
         * 배열의 마지막까지 도달했을 경우 마지막 값 리턴
         */

        if(index == firstDataSet.length-1){
            if(firstDataSet[index]%2==0)
                return firstDataSet[index] + secondDataSet[index];
        }

        /**
         *  홀수일때 동작 X
         */
        if(firstDataSet[index]%2!=0){
            return recursiveSum(index + 1);
        }

        int sum =0;

        if(firstDataSet[index]%2==0){
            sum += (firstDataSet[index] + secondDataSet[index]+ recursiveSum(index+1));
        }
        return sum;

    };
}

0개의 댓글