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]
  • 相关阅读:
    致 CODING 用户的元宵问候
    持续集成之理论篇
    基于 CODING 的 Spring Boot 持续集成项目
    使用 CODING 进行 Hexo 项目的持续集成
    使用 CODING 进行 Spring Boot 项目的集成
    三种前端模块化规范
    XSS和CSRF
    小问题填坑,关于obj.x和obj["x"]
    说一个闭包在实际开发中的应用
    关于return的分号自动插入问题
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13218412.html
Copyright © 2011-2022 走看看