2023.12.30每日一题

LeetCode每日一题

1185.一周中的第几天

1185. 一周中的第几天 - 力扣(LeetCode)

题目描述

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

输入为三个整数:daymonthyear,分别表示日、月、年。

您返回的结果必须是这几个值中的一个 {"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"

提示:

  • 给出的日期一定是在 19712100 年之间的有效日期。

方法一:蔡勒公式

蔡勒(Zeller)公式,是一个计算星期的公式,随便给一个日期,就能用这个公式推算出是星期几。

计算公式

2023.12.30每日一题_第1张图片

其中:

w:星期; w对7取模得:0-星期日,1-星期一,2-星期二,3-星期三,4-星期四,5-星期五,6-星期六

c:年份前两位

y:年份后两位

m:月(m大于等于3,小于等于14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月来计算,比如2003年1月1日要看作2002年的13月1日来计算)

d:日

**mod:**取余

代码
C++
class Solution {
public:
    string dayOfTheWeek(int day, int month, int year) {
        if(month < 3){
            month += 12;
            year -= 1;
        }
        int c = year / 100;
        int y = year % 100;
        int w = (c / 4 - 2 * c + y + y / 4 +13 * (month+1) / 5 + day - 1 ) % 7;
        vector weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        return weeks[(w + 7) % 7];
    }
};
Java
class Solution {
    public String dayOfTheWeek(int day, int month, int year) {
        if(month < 3){
            month += 12;
            year -= 1;
        }
        int c = year / 100;
        int y = year % 100;
        int w = (c / 4 - 2 * c + y + y / 4 + 13 * (month + 1) / 5 + day - 1) % 7;
        String[] weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday"};
        return weeks[(w + 7) % 7];
    }
}

方法二:

该题解:1185. 一周中的第几天 - 力扣(LeetCode)

代码
C++
class Solution {
public:
    string dayOfTheWeek(int day, int month, int year) {
        vector weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
        vector dayBeforeMOnth = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
        int days = 365 * (year - 1971) + (year - 1969) / 4 + dayBeforeMOnth[month - 1] + day;
        if((year % 400 == 0 || year % 4 == 0 && year % 100 != 0) && month >= 3) days++;
        return weeks[(days + 4) % 7];
        }
};
Java
class Solution {
    public String dayOfTheWeek(int day, int month, int year) {
        String[] weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday"};
        int[] dayBeforeMonth = new int[]{0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; 
        int days = 365 * (year - 1971) + (year - 1969) / 4 + dayBeforeMonth[month - 1] + day;
        if((year % 400 == 0 || year %4 == 0 && year % 100 != 0) && month >= 3) days++;
        return weeks[(4 + days) % 7];
    }
}

你可能感兴趣的:(算法学习,#,每日一题,算法,leetcode)