【LeetCode】【Math】day of the year

题目:

给定一个表示公历日期的字符串日期,格式为YYYY-MM-DD,请返回年份的天数。

Example 1:

Input: date = "2019-01-09"
Output: 9
Explanation: Given date is the 9th day of the year in 2019.

Example 2:

Input: date = "2019-02-10"
Output: 41

【解法】

闰年的判定方法:

①、普通年能被du4整除且不能被100整除的为闰年。(如zhi2004年就是闰年,1900年不dao是闰年)

②、世纪年能被400整除的是闰年。(如2000年是闰年,1900年不是闰年)

③、对于数值很大的年份,这年如果能整除3200,并且能整除172800则是闰年。如172800年是闰年,86400年不是闰年(因为虽然能整除3200,但不能整除172800)

def dayOfYear(self, date: str) -> int:
        Y, M, D = map(int, date.split('-'))
        days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if (M > 2 and Y % 4 ==0 and Y%100 != 0) or (M >2 and Y % 400 == 0):
            days[1] = 29
        for i in range(0,M-1):
            D += days[i]
        return D

 

Runtime: 20 ms, faster than 99.51% of Python3 online submissions for Day of the Year.

 

Memory Usage: 13.8 MB, less than 52.20% of Python3 online submissions for Day of the Year.
简洁一点的写法
class Solution:
    def dayOfYear(self, date: str) -> int:
        y, m, d = map(int, date.split('-'))
        days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if (y % 400) == 0 or ((y % 4 == 0) and (y % 100 != 0)): days[1] = 29
        return d + sum(days[:m-1])
Runtime: 28 ms, faster than 81.08% of Python3 online submissions for Day of the Year.
Memory Usage: 14 MB, less than 5.37% of Python3 online submissions for Day of the Year.
逻辑运输计算规则有三点:
1、再不加括号的情况下,同时出现 and 和 or ,先计算 and 在计算 or ;and优先级大于or
2、a or b ,结果只能是 a 或者 b ,a 为真结果是 a ,a为假结果是 b;
3、a and b ,结果只能是 a 或者 b,a为真结果是b,a为假结果是a ;

 

【解法二】

class Solution:
    def dayOfYear(self, date: str) -> int:
        Y, M, D = map(int, date.split('-'))
        return int((datetime.datetime(Y, M, D) - datetime.datetime(Y, 1, 1)).days + 1)
Runtime: 48 ms, faster than 8.11% of Python3 online submissions for Day of the Year.
Memory Usage: 14 MB, less than 5.37% of Python3 online submissions for Day of the Year.
 
 
 

 

posted @ 2020-07-03 18:41  桃花换小鱼干好不好  阅读(172)  评论(0)    收藏  举报