[SWEA] (D1) 2056. 연월일 달력

2024. 10. 13. 22:14·코딩테스트/SWEA

연월일 순으로 구성된 8자리의 날짜가 입력으로 주어진다.

 


해당 날짜의 유효성을 판단한 후, 날짜가 유효하다면

[그림1] 과 같이 ”YYYY/MM/DD”형식으로 출력하고,

날짜가 유효하지 않을 경우, -1 을 출력하는 프로그램을 작성하라.

연월일로 구성된 입력에서 월은 1~12 사이 값을 가져야 하며

일은 [표1] 과 같이, 1일 ~ 각각의 달에 해당하는 날짜까지의 값을 가질 수 있다.
 


※ 2월의 경우, 28일인 경우만 고려한다. (윤년은 고려하지 않는다.)

[입력]
입력은 첫 줄에 총 테스트 케이스의 개수 T가 온다.

다음 줄부터 각 테스트 케이스가 주어진다.

[출력]
테스트 케이스 t에 대한 결과는 “#t”을 찍고, 한 칸 띄고, 정답을 출력한다.

(t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)

 

[풀이]

년도는 검사하지 않아도 된다.

 

각 월별 최대 일수 배열을 검증을 위해 만들어준다.

 

검증 실패시 -1 입력후 다음 반복문으로 간다.

 

문자열 사이에 어떻게 `/`를 넣어야 할 지 고민했는데,

 

StringBuilder의 insert 기능을 이용해서 넣었다.

import java.util.*;
import java.lang.*;
import java.io.*;
 
class Solution {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
         
        int num = Integer.parseInt(br.readLine());
        int arrDay[] = {31,28,31,30,31,30,31,30,31,31,30,31,30,31};
         
        for(int i = 1 ; i <= num ; i++){
            String str = br.readLine();
            
            int month = Integer.parseInt(str.substring(4,6));
            int day = Integer.parseInt(str.substring(6,8));
            if(month < 1 || month > 12 ||
               day > arrDay[month -1] || day<1){
                System.out.println("#" +i + " -1");
                continue;
            }
             
            StringBuilder sb = new StringBuilder(str);
            sb.insert(4,"/");
            sb.insert(7,"/");
            System.out.println("#" + i + " " + sb);
        }
    }
}

 

[다른 사람의 풀이]

 

~~~~/~~/~~ 형식에 맞추는 거 빼고는 내 코드가 더 이해하기 쉽다고 생각한다.

 

다만 여기서는 int형으로 바로 변경하지 않고, String으로 받아온 후 if문에서 한 번만 int로 바꿔주었다.

 

그리고 나타낼때는 String으로 선언된 year, month, day를 출력하면 된다.

public class Solution2 {

	public static void main(String[] args) throws IOException{
		// TODO Auto-generated method stub

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int T;
		T = Integer.parseInt(br.readLine());

		int[] monthly = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
		
		for(int i= 1; i<=T; i++) {
			String date = br.readLine();
			String year = date.substring(0, 4);
			String month = date.substring(4, 6);
			String day = date.substring(6, 8);
			
			if(Integer.parseInt(month) >=1 && Integer.parseInt(month) <=12 && Integer.parseInt(day) >= 1 && Integer.parseInt(day) <= monthly[Integer.parseInt(month)]) {
				System.out.println("#" +i +" "+ year + "/" + month + "/" + day);
			}
			else System.out.println("#"+i+ " -1");
		}		
		br.close();
	}
}

 

[내 풀이에서 수정]

너무 Integer.parseInt를 많이 써서, 좋은 코드인지는 모르겠다.

import java.util.*;
import java.lang.*;
import java.io.*;

class Main {
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
        int num = Integer.parseInt(br.readLine());
        int arrDay[] = {31,28,31,30,31,30,31,30,31,31,30,31,30,31};
        
        for(int i = 1 ; i <= num ; i++){
            String str = br.readLine();
            
            String year = str.substring(0,4);
            String month = str.substring(4,6);
            String day = str.substring(6,8);
            
            if(Integer.parseInt(month) < 1 || 
               Integer.parseInt(month) > 12 ||
               Integer.parseInt(day) > arrDay[Integer.parseInt(month)-1] || 
               Integer.parseInt(day) < 1){
                System.out.println("#" +i + " -1");
                continue;
            }

            System.out.println("#" + i + " " + year + "/" + month + "/" + day);
        }
    }
}

 

문제 출처 : https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=1&contestProbId=AV5QLkdKAz4DFAUq&categoryId=AV5QLkdKAz4DFAUq&categoryType=CODE&problemTitle=&orderBy=PASS_RATE&selectCodeLang=ALL&select-1=1&pageSize=30&pageIndex=1

 

SW Expert Academy

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

swexpertacademy.com

 

'코딩테스트 > SWEA' 카테고리의 다른 글

[SWEA] (D2) 1859. 백만 장자 프로젝트  (1) 2024.10.15
[SWEA] (D2) 1945. 간단한 소인수분해  (0) 2024.10.14
[SWEA] (D1) 2071. 평균값 구하기  (0) 2024.10.13
[SWEA] (D1) 2072. 홀수만 더하기  (0) 2024.10.13
[SWEA] (D1) 2063. 중간값 찾기  (0) 2024.10.13
'코딩테스트/SWEA' 카테고리의 다른 글
  • [SWEA] (D2) 1859. 백만 장자 프로젝트
  • [SWEA] (D2) 1945. 간단한 소인수분해
  • [SWEA] (D1) 2071. 평균값 구하기
  • [SWEA] (D1) 2072. 홀수만 더하기
l0o0lv(한동근)
l0o0lv(한동근)
  • l0o0lv(한동근)
    개발하는 와플대조교
    l0o0lv(한동근)
  • 전체
    오늘
    어제
    • 분류 전체보기 (60)
      • SpringBoot (10)
      • 잡다한 개발지식 (1)
      • 코딩테스트 (47)
        • SWEA (43)
        • 프로그래머스 (0)
        • 백준 (4)
      • 알고리즘 (1)
      • 회고 (0)
      • 운동 (0)
  • 링크

    • Github
  • 인기 글

  • 최근 글

  • 태그

    prepersist
    coolsms
    websocket
    SWEA
    알고리즘
    백준
    실시간 쪽지
    MSA
    리버스 프록시
    어려웠던 문제
    cloudtype
    gitlab
    합 배열
    ec2
    webhook
    EUREKA
    무중단 배포
    springboot
    구간 합
    jenkins
  • hELLO· Designed By정상우.v4.10.0
l0o0lv(한동근)
[SWEA] (D1) 2056. 연월일 달력
상단으로

티스토리툴바