Leetcode 1154. 一年中的第几天
题目:
给你一个字符串 date ,按 YYYY-MM-DD
格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。
难度:简单题
示例1:
输入:date = "2019-01-09"
输出:9
解释:给定日期是2019年的第九天。
示例2:
输入:date = "2019-02-10"
输出:41
提示:
date.length == 10
date[4] == date[7] == '-'
,其他的date[i]
都是数字date
表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日
代码实现:
class Solution {
public:
// 闰年判断
bool isleap(int y) { return y % 4 == 0 && y % 100 != 0 || y % 400 == 0; }
// 月份天数
int Month[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int dayOfYear(string date) {
int day = 0;
int y, m, d;
sscanf(date.c_str(), "%d-%d-%d", &y, &m, &d);
Month[1] += isleap(y);
for(int i = 0; i < m - 1; ++i){
day += Month[i]; // 累加天数即可。
}
return day + d; // 加上最后不足一月的天数
}
};