1185. Day of the Week
SourceWeekly Contest 153 Q2DifficultyEasyRating1382
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: Library Functions
Thinking
Mapping a Gregorian date to a weekday is already in the standard library. Build the date and format its weekday name, without hand-rolled leap-year or month-length logic.
The simplest approach is to use the date library provided by the language to get the day of the week for the given year, month, and day.
The time complexity is \(O(1)\), and the space complexity is \(O(1)\).
1 2 3 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
Solution 2: Zeller's Congruence
Thinking
Method 1 needs a date library. Zeller's congruence computes the weekday from century, year-of-century, month, and day; January and February are months \(13\) and \(14\) of the previous year. No date type is required.
We can use Zeller's Congruence to calculate the day of the week. Zeller's Congruence is as follows:
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)\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |