Description
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"}.
Note: January 1, 1971 was a Friday.
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
1971and2100.
Solutions
Solution 1: Zeller's Congruence
We can use Zeller's Congruence to calculate the day of the week. Zeller's Congruence is as follows:
w = (\left \lfloor c⁄4 \right \rfloor - 2c + y + \left \lfloor y⁄4 \right \rfloor + \left \lfloor 13(m+1)⁄5 \right \rfloor + d - 1) \bmod 7
Where:
w: Day of the week (starting from Sunday)c: First two digits of the yeary: Last two digits of the yearm: Month (the range of m is from 3 to 14, that is, in Zeller's Congruence, January and February of a certain year are considered as the 13th and 14th month of the previous year. For example, January 1, 2003 is considered as the 1st day of the 13th month of 2002)d: Day⌊⌋: Floor function (round down)mod: Modulo operation
The time complexity is O(1), and the space complexity is O(1).
PythonJavaC++GoTypeScript
class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: return datetime.date(year, month, day).strftime('%A')(code-box)
Solution 2
PythonJava
class Solution: def dayOfTheWeek(self, d: int, m: int, y: int) -> str: if m < 3: m += 12 y -= 1 c = y // 100 y = y % 100 w = (c // 4 - 2 * c + y + y // 4 + 13 * (m + 1) // 5 + d - 1) % 7 return [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ][w](code-box)
