코딩테스트 공부
[LeetCode] 1154. Day of the Year - 자바스크립트 0621
codevil
2022. 6. 21. 11:34
https://leetcode.com/problems/day-of-the-year/submissions/
Day of the Year - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
주어진 년 월 일을 통해서 오늘이 그 해의 몇 번째 일인지 계산하는 문제이다. 이 문제에서 주의해야할 사항은
그 해가 윤년인가?
1. 문제를 먼저 풀기 위해서 주어진 date를 split 해야 했다.
const dateInfo = date.split("-")
2. 윤년인지 계산을 하기위해 함수를 만들었다. 계산공식은
2-1 400으로 나누어떨어지면 true
2-1 4로 나누어떨어 지지만 100으로 나누어떨어지면 false
2-2 4로 나누어떨어지면 true
2-3 그외에는 모두 false
function isBisextiles(year) {
if (year % 400 === 0) {
return true
} else if (year % 4 === 0 && year % 100 === 0) {
return false
} else if (year % 4 === 0) {
return true
}
return false
}
3. 1번에서 구한 연도의 정보와 2번에서 구한 함수를 통하여 이 해가 윤년인지 확인한다
const checkBisextiles = isBisextiles(Number(dateInfo[0]))
4. 달이 가지고 있는 정보를 입력한다.
const monthInfo = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
5. 3번의 값에 따라서 2월에 값을 더해준다
if (checkBisextiles === true) monthInfo[1] = monthInfo[1] + 1
6. 주어진 달의 값에 따라서 달의 정보가 있는 arr를 더해준다. 이러면 누적된 일을 알 수 있다
const month = Number(dateInfo[1]) - 1
const sum = monthInfo.slice(0, month).reduce((a, b) => a + b, 0)
7. 누적된 일 + 주어진 일을 return 한다
return Number(dateInfo[2]) + sum
전체 풀이
var dayOfYear = function (date) {
const dateInfo = date.split("-")
const checkBisextiles = isBisextiles(Number(dateInfo[0]))
const monthInfo = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if (checkBisextiles === true) monthInfo[1] = monthInfo[1] + 1
const month = Number(dateInfo[1]) - 1
const sum = monthInfo.slice(0, month).reduce((a, b) => a + b, 0)
return Number(dateInfo[2]) + sum
};
function isBisextiles(year) {
if (year % 400 === 0) {
return true
} else if (year % 4 === 0 && year % 100 === 0) {
return false
} else if (year % 4 === 0) {
return true
}
return false
}