본문 바로가기

알고리즘/문제 풀이

SW Expert Academy 1948. D2 날짜 계산기

SW Expert Academy

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

1.  내 코드

import java.util.*;


class Solution
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int test_case = sc.nextInt();
        for (int i = 1; i <= test_case; i++) {
            int total; // 날짜간의 차가 들어갈 변수
            // 첫 번째 달, 일 입력
            int M1 = sc.nextInt();
            int D1 = sc.nextInt();

            // 두 번째 달, 일 입력
            int M2 = sc.nextInt();
            int D2 = sc.nextInt();


            // day간의 차가 양수면 +, 음수면 -
            // +1 혹은 -1의 기준. 
            // 나는 만약에 5.5 ~8.15이면 4.30~8.10일로 바꿔서 푸는 것이다. 이때는 4.30일 하루가 더 늘어나므로 +1 
            // 만약 6.30~9.20 즉 d2<d1이면, 6.10~8.31일로 바꿔서 푸는 것 이때, 6.10일은 날짜 계산에 포함되므로, 
            // 달을 계산한 내용에서 빼줘야할 것은 1~9 즉 9일이다. 
            if(D2>=D1){
                total = monthCalculator(M2, M1, 0)+(D2-D1 +1);
            }else{
                total = monthCalculator(M2, M1, 0)-(D1-D2 -1);
            }
            System.out.printf("#%d %d\n",i, total);

        }
    }
    // 재귀함수 생성 -> 인수로 들어온 달이 무슨 달이냐에 따라 31이나 30을 축적
    // 인수로 들어온 M2가 M1과 같아질 때 재귀함수 종료, 그동안 쌓았던 일 수 출력
    static int monthCalculator(int M2, int M1, int dayAcc){
        if(M2 == M1){
            return dayAcc;
        }
        if(M2-1 == 1 || M2-1 == 3 || M2-1 == 5 || M2-1 == 7 || M2-1 == 8 || M2-1 == 10 || M2-1 == 12){
            dayAcc +=31;
            return monthCalculator(M2-1, M1, dayAcc);
        }
        else if(M2-1 == 4 || M2-1 == 6 || M2-1 == 9 || M2-1 == 11){
            dayAcc +=30;
            return monthCalculator(M2-1, M1, dayAcc);
        } else if (M2-1 ==2) {
            dayAcc +=28;
            return monthCalculator(M2-1, M1, dayAcc);
        }
        return 0;
    }
}