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 1971 and 2100.

💡 Hint 1:
Sum up the number of days for the years before the given year.

💡 Hint 2:
Handle the case of a leap year.

💡 Hint 3:
Find the number of days for each month of the given year.

Submitted Code

class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        start_year = 1971
        day_order = ["Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday"]
        
        total_days = 0
        for y in range(start_year, year):
            total_days += 366 if y % 400 == 0 or (y % 4 == 0 and y % 100 != 0) else 365
        
        feb_days = 29 if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0) else 28
        month_days = [31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        total_days += sum(month_days[:month-1]) + (day - 1)
        return day_order[total_days % 7]

Runtime: 0 ms | Beats 100.00%
Memory: 17.38 MB | Beats 90.14%

윤년만 주의하면 된다.

Other Solutions

1st

class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        daysInWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] #1
        DaysByMonthMod7 = [0,3,2,5,0,3,5,1,4,6,2,4]; # 2 (각 달이 시작될 때까지 누적일수  % 7)
        if(month < 3) : year = year - 1 # 3
        return daysInWeek[(year + (year//4 - year//100 + year//400) + DaysByMonthMod7[month-1] + day) % 7]; # 4

time complexity: 𝑂(1)
space complexity: 𝑂(1)

이 공식은 1년 1월 1일을 Monday라고 가정하고 기준일로 잡는다.

Leave a comment