# 1185. Day of the Week

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the `day``month` and `year` respectively.

Return the answer as one of the following values `{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}`.

Example 1:

``````Input: day = 31, month = 8, year = 2019
Output: "Saturday"
``````

Example 2:

``````Input: day = 18, month = 7, year = 1999
Output: "Sunday"
``````

Example 3:

``````Input: day = 15, month = 8, year = 1993
Output: "Sunday"
``````

Constraints:

• The given dates are valid dates between the years `1971` and `2100`.

``````class Solution {
public:
string dayOfTheWeek(int day, int month, int year) {
int totalDays = 4;
vector<int> monthDays{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
for (int i = 1971; i < year; ++i) {
totalDays += isLeapYear(i) ? 366 : 365;
}
for (int i = 1; i < month; ++i) {
totalDays += monthDays[i];
}
if (month > 2 && isLeapYear(year)) ++totalDays;
totalDays += day;
return days[totalDays % 7];
}
bool isLeapYear(int year) {
return year % 400 == 0 || (year % 100 != 0 && year % 4 == 0);
}
};
``````

``````// Zeller Formula
class Solution {
public:
string dayOfTheWeek(int day, int month, int year) {
vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
if (month < 3) month += 12, year -= 1;
int c = year / 100, y = year % 100, m = month, d = day;
int w = (c / 4 - 2 * c + y + y / 4 + 13 * (m + 1) / 5 + d - 1) % 7;
return days[(w + 7) % 7];
}
};
``````

``````// Sakamoto Algorithm
class Solution {
public:
string dayOfTheWeek(int day, int month, int year) {
vector<string> days{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
vector<int> t{0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
if (month < 3) year -= 1;
return days[(year + (year / 4 - year / 100 + year / 400) + t[month - 1] + day) % 7];
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1185

https://leetcode.com/problems/day-of-the-week/

https://leetcode.com/problems/day-of-the-week/discuss/377384/JavaC%2B%2BPython-Zeller-Formula

https://leetcode.com/problems/day-of-the-week/discuss/381894/JavaC%2B%2BPython3-Sakamoto-Algorithm

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation