프로그래머스 Lv.0 날짜 비교하기

정수 배열 date1과 date2가 [year, month, day] 꼴로 주어진다.
두 배열의 날짜를 비교했을 때
date1이 date2 보다 앞서는 날짜라면 return 1,
아니면 return 0을 하는 문제
** 풀이방법
배열의 원소들을
문자열로 합쳐서 날짜형식으로 변환시키고,
메소드를 사용해 날짜를 비교한다.
- java.time패키지의 LocalDate 클래스를 사용해 날짜 형식으로 변환
static LocalDate of (int year, int month, int dayOfMonth)
LocalDate localDate1 = LocalDate.of(date1[0],date1[1],date1[2]);
LocalDate localDate2 = LocalDate.of(date2[0],date2[1],date2[2]);
- isBefore()메서드를 사용해 이전 날짜인지 비교
boolean isAfter(ChronoLocalDate other) //주어진 날짜가 매개변수 날짜의 이후 날짜인지 비교
boolean isBefore(ChronoLocalDtae other) //주어진 날짜가 매개변수 날짜의 이전 날짜인지 비교
boolean isEqual(ChronoLocalDate other) //주어진 날짜가 매개변수 날짜와 같은지 비교
if (localDate1.isBefore(localDate2))
answer=1;
<> 전체코드 </>
import java.time.LocalDate;
class Solution {
public int solution(int[] date1, int[] date2) {
int answer = 0;
//날짜로 변환
LocalDate localDate1 = LocalDate.of(date1[0],date1[1],date1[2]);
LocalDate localDate2 = LocalDate.of(date2[0],date2[1],date2[2]);
//날짜 비교
if (localDate1.isBefore(localDate2))
answer=1;
return answer;
}
}
반응형
'개발로그 > 알고리즘' 카테고리의 다른 글
프로그래머스 Lv.0 외계행성의 나이 (0) | 2023.07.14 |
---|---|
프로그래머스 Lv.0 한 번만 등장한 문자 (0) | 2023.07.13 |
프로그래머스 Lv.1 예산 (0) | 2023.07.12 |
프로그래머스 Lv.0 모스부호(1) (0) | 2023.07.11 |
프로그래머스 Lv.1 성격 유형 검사하기 (0) | 2023.07.06 |
댓글