알고리즘/삼성 SW_Expert

<삼성 SW Expert Academy> 2056번 연월일 달력 java 문제풀이

Han_5ung 2022. 1. 4. 23:41

문제 출처

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=1&contestProbId=AV5QLkdKAz4DFAUq&categoryId=AV5QLkdKAz4DFAUq&categoryType=CODE&problemTitle=&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=1&pageSize=10&pageIndex=1 

 

SW Expert Academy

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

swexpertacademy.com

 

문제

연월일로 구성된 8자리 숫자의 유효성을 판단한 후 날짜가 유효하다면

YYYY/MM/DD/ 형식으로 출력

하고 유효하지 않을 경우 -1를 출력하라.

 

풀이

import java.util.Scanner;
import java.io.FileInputStream;
 
class Solution
{
    public static int arr[] = { 0, 31, 28, 31, 30, 31, 30, 31, 30, 31, 30, 31 }; //월별 최대 일수를 배열로 저장
     
    public static void main(String args[]) throws Exception
    {
        String str; //입력 받을 8자리 날짜 문자열 저장
        int tc;     //테스트 케이스
        Scanner sc = new Scanner(System.in);
        tc = sc.nextInt();
        for (int i = 1; i <= tc; i++) {
            str = sc.next();
            int year = Integer.parseInt(str.substring(0, 4)); //문자열 4자리를 잘라 정수형 year에 저장
            int month = Integer.parseInt(str.substring(4, 6)); //문자열 인덱스 4부터 5까지 잘라 month에 저장
            int day = Integer.parseInt(str.substring(6, 8));   //문자열 인덱스 6부터 7까지 잘라 day에 저장
            if (month < 13 && month > 0 && day <= arr[month])
                System.out.println("#"+i+" "+getYear(year) + "/" + getMonth(month) + "/" + getDay(day));
            else
                System.out.println("#"+i+" -1");
        }
    }
    public static String getYear(int a) {   
        return String.format("%04d", a);  //입력 받은 정수값을 4자리로 표현
    }
 
    public static String getMonth(int a) {
        return String.format("%02d", a); //2자리로 표현
    }
 
    public static String getDay(int a) {
        return String.format("%02d", a);
    }
}

문자열로 8자리 수를 입력받아 substring함수를 사용하여

문자열을 필요한 만큼 자르고 Integer.pareInt로 문자열 -> 정수형으로 전환하였다.

출력하는 과정에서 0101인 경우 101로 출력하는 문제점을 해결하기 위해

String.format으로 정수값의 자리수를 고정시켜 출력하였다.