Problem Solving/리트코드(leetcode)
[Leetcode/C++] 1154. Day of the Year
높은곳에영광
2022. 1. 28. 17:15
class Solution {
public:
int dayOfYear(string date) {
int answer = 0;
int data = stoi(date.substr(5,2)) -1;
int year = stoi(date.substr(0,4));
for(; data > 0; data--) {
if(data == 2) {
answer += 28;
if(year % 400 == 0 && year % 100 ==0 && year % 4 ==0) {
answer += 1;
}
else if(year % 100 != 0 && year % 4 == 0) answer += 1;
}
else if(data < 8 && data % 2 == 1) answer += 31;
else if(data > 7 && data % 2 == 0) answer += 31;
else answer += 30;
}
int daya = stoi(date.substr(8,2));
answer += daya;
return answer;
}
};
C프로그래밍을 처음 배울 때 달력을 구현했던 것과 비슷한 로직으로 구현하였습니다.
현재 달에서 -1만큼 개월만큼 일로 환산하고 윤년이라면 2월에 1일을 추가합니다.
이후 1,3,5,7 / 8,10,12 월은 31일이므로 해당날짜만 if문으로 31일을 걸어주고 남은 일수만큼 더하여 출력하는 단순한 문제입니다.
문제: https://leetcode.com/problems/day-of-the-year/
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