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"}
.
这题有三种解法,
一是 利用Zeller Formula去计算,这个公式是什么感兴趣自己查。我没兴趣
二是知道1971-01-01这天是星期几,然后计算给出的时间到整天的天数,%7就得到是星期几
三是不需要知道1971-01-01是星期几,只需要知道今天是星期几,然后计算今天到1971-01-01的天数,目标日期到1971-01-01的天数,两个天数做个diff 然后% 7,就能知道是星期几了。
class Solution(object): def dayOfTheWeek(self, day, month, year): """ :type day: int :type month: int :type year: int :rtype: str """ def hasLeapDay(year): return 1 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else 0 # 2020 07 01 dayNames = ["Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday"] daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # days since 31, 12, 1970 def daysSinceStart(day, month, year): numDays = 0 for y in range(year - 1, 1970, -1): numDays += 365 + hasLeapDay(y) numDays += sum(daysInMonth[:month-1]) numDays += day if month > 2: numDays += hasLeapDay(year) return numDays knownStart = daysSinceStart(1,7,2020) d = daysSinceStart(day, month, year) return dayNames[ (d - knownStart) % 7]