1185.一周中的第几天
链接:1185.一周中的第几天
难度:Easy
标签:数学
简介:给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
题解 1 - python
- 编辑时间:2023-12-30
- 执行用时:36ms
- 内存消耗:17.09MB
- 编程语言: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 dayOfTheWeek(self, day: int, month: int, year: int) -> str:
            months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30]
            if isLeapYear(year): months[1] = 29
            day += sum(365 + isLeapYear(y) for y in range(1971, year)) + sum(months[:month - 1])
            return weeks[(day + 3) % 7]
题解 2 - cpp
- 编辑时间:2022-01-04
- 内存消耗:5.9MB
- 编程语言:cpp
- 解法介绍:遍历求出距离第一天的天数并取模。
string names[] = {"Friday",  "Saturday",  "Sunday",  "Monday",
                  "Tuesday", "Wednesday", "Thursday"};
int isLeapYear(int year) {
    return year % 400 == 0 || year % 100 != 0 && year % 4 == 0;
}
class Solution {
   public:
    string dayOfTheWeek(int day, int month, int year) {
        int months[] = {
            0,  31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31,
            30, 31};
        while (month) day += months[--month];
        while (year > 1971) day += isLeapYear(--year) ? 366 : 365;
        return names[(day - 1) % 7];
    }
};