1154.一年中的第几天
链接:1154.一年中的第几天
难度:Easy
标签:数学、字符串
简介:给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。请你计算并返回该日期是当年的第几天。
题解 1 - cpp
- 编辑时间:2021-12-21
- 执行用时:16ms
- 内存消耗:5.8MB
- 编程语言:cpp
- 解法介绍:检测闰年和前面有几个月。
class Solution {
public:
int monthDay[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
void checkLeapYear(int year) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
monthDay[2] = 29;
}
}
int dayOfYear(string date) {
int year = 0, month = 0, day = 0;
for (int i = 0; i < 4; i++) year = year * 10 + date[i] - '0';
for (int i = 5; i < 7; i++) month = month * 10 + date[i] - '0';
for (int i = 8; i < 10; i++) day = day * 10 + date[i] - '0';
checkLeapYear(year);
// printf("year = %d, month = %d, day = %d", year, month, day);
int ans = day;
for (int i = 1; i < month; i++) ans += monthDay[i];
return ans;
}
};
题解 2 - python
- 编辑时间:2023-12-31
- 执行用时:48ms
- 内存消耗:17.11MB
- 编程语言:python
- 解法介绍:直接计算。
def isLeapYear(year: int) -> bool:
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
weeks = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
class Solution:
def dayOfYear(self, date: str) -> int:
year, month, day = int(date[:4]), int(date[5:7]), int(date[8:])
months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30]
if isLeapYear(year): months[1] = 29
return sum(months[:month - 1]) + day