1154. Day of the Year
https://leetcode.com/problems/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
给一个以xxxx-xx-xx为格式的日期,问是那年的第几天。把每个月的天数列出来,然后遍历到指定月的前一个月加起来。判断月是不是>2且年是不是闰年,是就天数再加1。
代码参考自这。
class Solution {
public:
int dayOfYear(string date) {
vector<int> days{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int y = stoi(date.substr(0, 4)), m = stoi(date.substr(5, 2)), d = stoi(date.substr(8, 2));
if (m > 2 && y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ++d;
while (--m > 0) d += days[m - 1];
return d;
}
};
Last updated
Was this helpful?