LeetCode|1185.一周中的第几天

LeetCode习题答案汇总

题目:
给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。

输入为三个整数:day、month 和 year,分别表示日、月、年。

您返回的结果必须是这几个值中的一个 {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}。

示例 1:

输入:day = 31, month = 8, year = 2019
输出:“Saturday”
示例 2:

输入:day = 18, month = 7, year = 1999
输出:“Sunday”
示例 3:

输入:day = 15, month = 8, year = 1993
输出:“Sunday”

提示:

给出的日期一定是在 1971 到 2100 年之间的有效日期。

分析:

  • 1971.1.1是周五
  • 首先定义一个函数判断年份是否为闰年
  • 计算日期的话,是从1971年开始计算,先加年份,再加月份,最后加上日
  • 由于一开始是周五,所以需要在取余前先加5

代码:

class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        commom_year = [31,28,31,30,31,30,31,31,30,31,30,31]
        leap_year = [31,29,31,30,31,30,31,31,30,31,30,31]
        weeks = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
        
        def judgeYear(year):
            # 判断是否为闰年
            if year % 400 == 0:
                return True
            elif year % 100 == 0:
                return False
            elif year % 4 == 0:
                return True
        
        
        days = 0
        start_year = 1971
        while year > start_year:
            if judgeYear(start_year):
                days += 366
                start_year += 1
            else:
                days += 365
                start_year += 1
        start_month = 1
        while start_month < month:
            if judgeYear(year):
                days += leap_year[start_month-1]
            else:
                days += commom_year[start_month-1]
            start_month += 1
        days += day-1
        return weeks[(days+5)%7]

结果:
LeetCode|1185.一周中的第几天_第1张图片

你可能感兴趣的:(LeetCode,leetcode,python)