leetcode:1154. 一年中的第几天
题目
给你一个字符串 date
,按 YYYY-MM-DD
格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。
示例:
输入:date = "2019-01-09"
输出:9
解释:给定日期是2019年的第九天。
输入:date = "2019-02-10"
输出:41
解答 & 代码
class Solution {
public:
int dayOfYear(string date) {
int year = stoi(date.substr(0, 4));
int month = stoi(date.substr(5, 2));
int day = stoi(date.substr(8, 2));
// 每个月的天数
vector<int> monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 如果是闰年,则二月天数为 29 天
// 闰年:1)普通闰年:年份是 4 的倍数且不是 100 的倍数;2)实际闰年:年份是 400 的倍数
if((year % 100 != 0 && year % 4 == 0) || year % 400 == 0)
monthDays[1] = 29;
// 计算是一年中的第几天
int result = 0;
for(int i = 0; i < month - 1; ++i)
result += monthDays[i];
result += day;
return result;
}
};
复杂度分析:
- 时间复杂度 O(1):日期字符串长度和一年的月份数都是常数
- 空间复杂度 O(1):
执行结果:
执行结果:通过
执行用时:24 ms, 在所有 C++ 提交中击败了 21.72% 的用户
内存消耗:6.8 MB, 在所有 C++ 提交中击败了 13.29% 的用户