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
and2100
.
Solution: LeapYear
Time complexity: O(1)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua inline bool leapYear(int y) { return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0); } class Solution { public: string dayOfTheWeek(int day, int month, int year) { vector<string> names = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; vector<int> days = {31, 28 + leapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int sum = 0; for (int i = 1970; i < year; ++i) sum += 365 + leapYear(i); for (int i = 1; i < month; ++i) sum += days[i - 1]; sum += day; return names[(sum + 3) % 7]; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment