import java.util.*;
class Solution {
public String solution(int a, int b) {
/*
a월 b일 무슨 요일
answer = 요일
윤년 2월 29일까지 있음
31 : 1,3,5,7,8,10,12
이외 : 2,4,6,9,11
key : value
*/
String[] days = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
//요일은 쭉 이어진다.
//7로 나눈 나머지라고 할 수 있다.
// 예를 들어 2016년을 1월 1일 부터 진행할때 금요일이다.
//2016.01.01이 금요일이다. 여기서부터 쭉 더해지면 된다.
//+1 -> 금 +2 -> 토 +3 -> 일 +4: 월 5화6수7목+8금
Map<Integer, Integer> cal = new HashMap<>();
cal.put(1, 31);
cal.put(2, 29);
cal.put(3, 31);
cal.put(4, 30);
cal.put(5, 31);
cal.put(6, 30);
cal.put(7, 31);
cal.put(8, 31);
cal.put(9, 30);
cal.put(10, 31);
cal.put(11, 30);
cal.put(12, 31);
int count = 0;
for(int i=1; i<=a-1; i++){
count += cal.get(i);
System.out.println(count);
}
count += b;
System.out.println(count);
//index 조정 : index == 0일때 sun이여야 하나 1월 1일이 금요일(+1일) 이기 때문에
//index == 0일때 목요일이 나옴
//그러므로 7로 나눈 나머지에 index +4 만큼 해준다.
int index = ((count % 7) + 4) %7;
return days[index];
}
}
분석
2016년의 1월 1일을 0으로 가정하고 해당 월,일을 더해주었다.
요일 배열에서는 인덱스 0이 sun이므로 1월1일이 금요일(+1일)인 index를 맞추기 위해서 +4를 해주었다.
1월 1일이 +1일이 되었고 금요일이기 때문에 index 0은 목요일이므로 (일 - 0, 월 - 1, 화 - 2, 수 - 3, 목 - 4) +4를 해주면 된다.
+4를 해주었을때 7이상이 될 수도 있기 때문에 다시 7로 나눈 나머지의 인덱스를 구하였다.
참고할 만한 정답
자바 내장함수를 사용
알고리즘 테스트에서는 내 정답과 비슷하게 풀기를 원하겠지만 실무에서는 아래와 같은 방법이 맞을듯 싶다.
//문제가 변형되어 현재 문제에 맞게 참고 정답 변경
import java.util.*;
class Solution {
public String solution(int a, int b) {
Calendar cal = new Calendar.Builder().setCalendarType("gregory")
.setDate(2016, a - 1, b).build();
return cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, new Locale("US")).toUpperCase();
}
}