返回
运筹帷幄,决胜千里:LeetCode刷题——一年中的第几天
闲谈
2023-11-01 15:54:56
踏上LeetCode算法学习之旅,我们继续前进,今天要挑战的是一个有趣的题目——“一年中的第几天”。在这道题中,你需要根据给定的日期字符串,计算出该日期是当年的第几天。
让我们从题目要求开始理解:
- 输入:一个按YYYY-MM-DD格式表示的日期字符串date。
- 输出:一个整数,表示date是当年的第几天。
为了解决这个问题,我们可以采用以下步骤:
- 将日期字符串date拆分成年月日三个部分。
- 根据年、月、日,计算出该日期是当年的第几天。
- 将计算结果返回。
下面是Python代码实现:
def day_of_year(date):
"""
计算一年中的第几天。
Args:
date (str): 日期字符串,格式为YYYY-MM-DD。
Returns:
int: 一年中的第几天。
"""
# 将日期字符串拆分成年月日三个部分。
year, month, day = map(int, date.split('-'))
# 计算出当年的总天数。
total_days = 365
# 如果是闰年,则总天数为366天。
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
total_days = 366
# 计算出每个月的天数。
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# 如果是闰年,则2月有29天。
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
month_days[1] = 29
# 计算出该日期是当年的第几天。
day_of_year = sum(month_days[:month - 1]) + day
# 返回结果。
return day_of_year
if __name__ == '__main__':
# 测试代码。
date = '2023-03-08'
day_of_year = day_of_year(date)
print(f'{date}是当年的第{day_of_year}天。')
运行结果:
2023-03-08是当年的第67天。
在代码中,我们首先将日期字符串date拆分成年月日三个部分,然后根据年、月、日计算出该日期是当年的第几天。最后,我们将计算结果返回。
通过这道题目,我们不仅学习了如何计算一年中的第几天,还巩固了Python中的日期处理知识。希望大家能够继续坚持刷题,提升自己的算法技能!