题目:给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
输入:三个整数:year(年),month(月),day(日)
输出:字符串星期:“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”
范围:给出的日期一定是在 1971 到 2100 年之间的有效日期。
这题目不难,很简单。了解闰年平年的规则就基本能做出了。我之所以要记录下这道题,是因为有个神奇的魔法解法(基姆拉尔森公式)。
闰年规则:四年一闰,百年不闰,四百年再闰
解法:(python语言)
区别出平年与闰年,先算年的天数差,再算月的天数差,最后算日的天数差,得到总的天数差后取模计算。
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
monthday={
1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
week={
0:'Friday',1:'Saturday',2:'Sunday',3:'Monday',4:'Tuesday',5:'Wednesday',6:'Thursday',} #1971.1.1是星期五
allday=0 #记录1971.1.1到指定日期的天数差
for index in range(1971,year):
if (index%4==0 and index%100!=0) or index%400==0:#闰年
allday+=366
else:#平年
allday+=365
if ((year%4==0 and year%100!=0) or year%400==0) and month>2:
monthday[2]=29 #也可以直接写成allday+=1,就不用修改字典的数据,执行速度会更快
for index in range(1,month):
allday+=monthday.get(index)
allday+=day-1
return week.get(allday%7)
python有一个datatime库,专门处理时间
import datetime
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
obj = datetime.date(year,month,day)
return obj.strftime('%A') #返回完整的星期名称格式
基姆拉尔森计算公式:(day+2month+3(month+1)/5+year+year/4-year/100+year/400+1)%7
class Solution:
def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
week={
0:'Sunday',1:'Monday',2:'Tuesday',3:'Wednesday',4:'Thursday',5:'Friday',6:'Saturday'}
if month==1 or month==2:
year-=1
month+=12
return week.get((day+2*month+3*(month+1)//5+year+year//4-year//100+year//400+1)%7)
END!