给你一个字符串 date
,按 YYYY-MM-DD
格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。
输入:date = "2019-01-09" 输出:9 解释:给定日期是2019年的第九天。
第一遍错误: "2012-01-02"
class Solution(object): def dayOfYear(self, date): """ :type date: str :rtype: int """ ans=0 year=int(date[:4]) month=int(date[5:7]) day=int(date[8:]) md=[31,28,31,30,31,30,31,31,30,31,30,31] for i in range(0,month-1): ans=ans+md[i] if(year%400==0 or(year%4==0 and year%100!=0)): ans=ans+1 return(ans+day)
闰年的1月2日 没经过2月29 不需要加一天
第二遍 语法错误
第三遍
class Solution(object): def dayOfYear(self, date): """ :type date: str :rtype: int """ ans=0 year=int(date[:4]) month=int(date[5:7]) day=int(date[8:]) md=[31,28,31,30,31,30,31,31,30,31,30,31] for i in range(0,month-1): ans=ans+md[i] if((year%400==0 or(year%4==0 and year%100!=0))and (month>2 or(month==2 and day==29))): ans=ans+1 return(ans+day)
多算了一天 2月29日 29已经在day里面了 if判断又多加了一天
第四遍 Finally
class Solution(object): def dayOfYear(self, date): """ :type date: str :rtype: int """ ans=0 year=int(date[:4]) month=int(date[5:7]) day=int(date[8:]) md=[31,28,31,30,31,30,31,31,30,31,30,31] for i in range(0,month-1): ans=ans+md[i] if((year%400==0 or(year%4==0 and year%100!=0))and (month>2)): ans=ans+1 return(ans+day)
标签:int,1154,31,30,month,ans,date From: https://www.cnblogs.com/LYoungH/p/17096701.html