본문 바로가기

CodingTEST

[SW Expert D2] 1948. 날짜 계산기

반응형

1948. 날짜 계산기

 

SW Expert Academy

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

swexpertacademy.com

 

 

문제 분석

 

  • 월 일로 이루어진 날짜를 2개 입력 받아, 두 번째 날짜가 첫 번째 날짜의 며칠째인지 출력하는 프로그램을 작성하라.

 

해결 포인트

 

  • 각 월에 따른 일을 배열로 제작
    • 1/31, 2/28, 3/31, 4/30, 5/31, 6/30, 7/31, 8/31, 9/30, 10/31, 11/30, 12/31
  • 같은 달일 경우, 두번째 날 - 첫번째 날
  • 다른 달일 경우, 중간 월에 따른 최대 일을 모두 더하고 첫번째 날, 두번째 날 더한다.

 

코드

 

import java.util.Arrays;
import java.util.Scanner;
import java.io.FileInputStream;

class Solution
{
    public static void main(String args[]) throws Exception
    {
        //System.setIn(new FileInputStream("res/input.txt"));
        Scanner sc = new Scanner(System.in);
        int T;
        T=sc.nextInt();

        for(int test_case = 1; test_case <= T; test_case++) {
            int[] month = {31,28,31,30,31,30,31,31,30,31,30,31};

            int firstMonth = sc.nextInt();
            int firstDay = sc.nextInt();
            int secondMonth = sc.nextInt();
            int secondDay = sc.nextInt();

            int result = 0;
            if(firstMonth == secondMonth) {
                result = secondDay - firstDay + 1;
            }
            else {
                result = month[firstMonth-1] - firstDay + 1;
                for (int i = firstMonth; i < secondMonth - 1; i++) {
                    result += month[i];
                }
                result += secondDay;
            }


            System.out.printf("#%d %d\n", test_case, result);
        }
    }
}
반응형