zoukankan      html  css  js  c++  java
  • 1185. Day of the Week

    Given a date, return the corresponding day of the week for that date.

    The input is given as three integers representing the daymonth 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]
  • 相关阅读:
    C/C++中0xcccccccc...
    函数指针定义
    Visual C++的DLL
    RGB
    链接指示:extern "C"
    for_each用法
    漫画 | 夜深了,程序员的电脑却没关,发生了这样的故事…
    漫画 | 小公司卧薪尝胆三年,意外拿到美团offer
    Java 可变参数
    使用程序往Neo4j导入CSV报错
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13218412.html
Copyright © 2011-2022 走看看