

<삼성 SW Expert Academy> 2056번 연월일 달력 java 문제풀이알고리즘/삼성 SW_Expert2022. 1. 4. 23:41
Table of Contents
문제 출처
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으로 정수값의 자리수를 고정시켜 출력하였다.
'알고리즘 > 삼성 SW_Expert' 카테고리의 다른 글
<삼성 SW Expert Academy> 2050번 알파벳을 숫자로 변환 java 문제풀이 (2) | 2022.01.05 |
---|---|
<삼성 SW Expert Academy> 2072번 홀수만 더하기 java 문제풀이 (0) | 2021.12.31 |

@Han_5ung :: 한성 개인 기록장
IT
github : https://github.com/HanSungHyeon