Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

 

Example 1:

Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.
Example 2:

Input: date = "2019-02-10"
Output: 41
Example 3:

Input: date = "2003-03-01"
Output: 60
Example 4:

Input: date = "2004-03-01"
Output: 61
 

Constraints:

date.length == 10
date[4] == date[7] == '-', and all other date[i]'s are digits
date represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.

这题不难,主要是有个规则,被100整除的年份,必须得被400整除才是润年。我这里偷懒了,没有使用数组去存,懒得改了。

class DayOfTheYear : public Solution {
    public:
    void Exec() {
        auto res = dayOfYear("1900-03-25");
    }
    int dayOfYear(string date) {
        unordered_map<int, int> month_day_map = {
            {1, 31},
            {3, 31},
            {4, 30},
            {5, 31},
            {6, 30},
            {7, 31},
            {8, 31},
            {9, 30},
            {10, 31},
            {11, 30},
            {12, 31}
        };

        size_t prev_pos = 0;
        size_t pos = date.find("-", 0);
        string year_str = date.substr(0, pos - 1 + 1);
        prev_pos = pos + 1;
        pos = date.find("-", prev_pos);
        string month_str = date.substr(prev_pos, pos - 1 - prev_pos + 1);
        string day_str = date.substr(pos + 1);

        int year = atoi(year_str.c_str());
        int month = atoi(month_str.c_str());
        int day = atoi(day_str.c_str());

        if (year % 4 == 0) {
            month_day_map[2] = 29;
            if (year % 100 == 0 && year % 400 != 0) {
                month_day_map[2] = 28;
            }
        } else {
            month_day_map[2] = 28;
        }

        int result = 0;
        for (int i = 1; i < month; i++) {
            result += month_day_map[i];
        }
        result += day;

        return result;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day