본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1154. Day of the Year

반응형

https://leetcode.com/problems/day-of-the-year/description/

 

Day of the Year - LeetCode

Can you solve this real interview question? Day of the Year - Given a string date representing a Gregorian calendar [https://en.wikipedia.org/wiki/Gregorian_calendar] date formatted as YYYY-MM-DD, return the day number of the year.   Example 1: Input: dat

leetcode.com

📕 풀이방법

📔 입력 및 초기화

1. 윤년과 평년에 대한 12월의 일자를 배열형태로 저장합니다.

2. yyyy-mm-dd 형식의 date가 인자로 들어오기 때문에 year, month, day를 substring으로 date를 나눠 int로 저장이 가능합니다. 

3. 정답 변수 ans를 선언해줍니다.

📔 풀이과정

1. 400으로 나누어 떨어지거나 4로 나눠떨어지며 100의 배수가 아니면 윤년이므로 isLeap에 여부를 저장합니다.

2. month이전까지 for loop를 수행하면서 ans에 누적해 해당하는 날을 더해줍니다.

📔 정답 출력 | 반환

ans를 반환합니다.


📕 Code

📔 C++

class Solution {
    int dayPerMonth[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 
    int dayPerMonthLeap[13] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 
public:
    int dayOfYear(string date) {
        int year = stoi(date.substr(0,4));
        int month = stoi(date.substr(5,2));
        int day = stoi(date.substr(8,2));
        int isLeap = (year % 400 == 0) || ((year % 4 == 0) && (year % 100) != 0); 
        int ans = day;
        for(int i = 1; i < month; i++) {
            ans += isLeap ? dayPerMonthLeap[i] : dayPerMonth[i];
        }
        return ans;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.