1154. Day of the Year

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.

这道题给了一个 年-月-日 的日期字符串,让我们返回该年已经过了多少天。关于每月各多少天,小学的时候就已经背的滚瓜烂熟了吧,一三五七八十腊,三十一天永不差。唯一有变化的就是二月了,闰年是 29 天,所以这里唯一的难点就是判断闰年了吧。先用个数组列出非闰年各个月的天数,然后分别从给定 date 字符串中提取出年月日,并转为整型数。然后将当前月之前的天数都累加到结果 res 中,接下来判断当前月是否大于2月,没有的话都不用判断闰年了。超过了2月就要判断当前年是否是闰年,判断方法很简单,若能被 400 整除,一定是闰年,或着不能被 100 整除,但能被4整除的也是闰年。是闰年的话就再多加一天,最后再加上当前的天数返回即可,参见代码如下:

class Solution {
public:
    int dayOfYear(string date) {
        vector<int> monthDays{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int res = 0, year = stoi(date.substr(0, 4)), month = stoi(date.substr(5, 2)), day = stoi(date.substr(8, 2));
        for (int i = 0; i < month - 1; ++i) {
            res += monthDays[i];
        }
        if (month > 2 && (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))) {
            ++res;
        }
        return res + day;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1154

参考资料:

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

https://leetcode.com/problems/day-of-the-year/discuss/355916/C%2B%2B-Number-of-Days-in-a-Month

LeetCode All in One 题目讲解汇总(持续更新中…)


转载请注明来源于 Grandyang 的博客 (grandyang.com),欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 grandyang@qq.com

💰


微信打赏


Venmo 打赏

×

Help us with donation