[Leetcode] 1154. Day of the Year (C++)

Algorithm|2021. 11. 29. 15:54
반응형
 

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월 2월은 윤년이어도 하루를 더하면 안됨
class Solution {
public:
    int dayOfYear(string date) 
    {
        int sum = 0;
        int year = stoi(date.substr(0,4));
        int mon = string_to_int(date.substr(5,2));
        int day = string_to_int(date.substr(8,2));
        vector<int> m_d = {31,28,31,30,31,30,31,31,30,31,30,31};
        
        if(mon == 1) return day;
        
        if(mon != 2)
            sum += is_yoon(year);
        
        for(int i=0; i<mon-1; i++)
        {
            sum += m_d[i];
        }
        
        return sum + day;
    }
    
    int is_yoon(int year)
    {
        if(year % 4 == 0)
        {
            if(year % 100 == 0)
            {
                if(year % 400 == 0)
                    return 1;
                return 0;
            }
            return 1;
        }
        return 0;
    }
    
    int string_to_int(string s)
    {
        if(s[0] == '0')
            return s[1] - '0';
        else
            return stoi(s);
    }
};
반응형

댓글()