1154. 一年中的第几天

给你一个按 YYYY-MM-DD 格式表示日期的字符串 date,请你计算并返回该日期是当年的第几天。

通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。每个月的天数与现行公元纪年法(格里高利历)一致。

class Solution(object):
    def dayOfYear(self, date):
        """
        :type date: str
        :rtype: int
        """
        s = date.split("-")
        res = 0
        year=int(s[0])
        month=int(s[1])
        day=int(s[2])
        d={
            1:31,
            2:28,
            3:31,
            4:30,
            5:31,
            6:30,
            7:31,
            8:31,
            9:30,
            10:31,
            11:30,
            12:31
        }
        for i in range(1,month):
            res+=d[i]
        if (year%400==0 or (year%4==0 and year%100!=0)) and month>=3:
            res+=1
        return (res+day) 

class Solution:
    def dayOfYear(self, date: str) -> int:
        y,m,d=map(int,date.split("-"))
        h=[0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if (y%400==0 or (y%4==0 and y%100!=0)):
            h[2]+=1
        return sum(h[:m])+d
发布了216 篇原创文章 · 获赞 17 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_36328915/article/details/105044829