给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
输入为三个整数: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
年之间的有效日期。蔡勒(Zeller)公式,是一个计算星期的公式,随便给一个日期,就能用这个公式推算出是星期几。
计算公式
其中:
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:**取余
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<string> weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
return weeks[(w + 7) % 7];
}
};
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)
class Solution {
public:
string dayOfTheWeek(int day, int month, int year) {
vector<string> weeks = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
vector<int> 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];
}
};
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];
}
}