--- title: 'LeetCode 1154. Day of the Yearr' disqus: hackmd --- # LeetCode 1154. Day of the Year ## Description Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. ## Example Input: date = "2019-01-09" Output: 9 Explanation: Given date is the 9th day of the year in 2019. Input: date = "2019-02-10" Output: 41 ## Constraints * date.length == 10 * date[4] == date[7] == '-', and all other date[i]'s are digits * date represents a calendar date between Jan 1st, 1900 and Dec 31^th^, 2019. ## Answer 此題是計算該年1/1至給定的日期共有幾天,首先將年月日都先讀取出來,然後用一個for從1月開始算,算到給定的月份前,其中在計算日期的時候還要判斷現在是不是閏年,若是的話2月就有29天,在月份日期的規律中,8月以下的奇數月有31天,除2月以外的偶數月有30天,從8月開始就是反過來,如此依序疊加日期,最後再加上題目給定的天數即為答案。 判斷閏年就是用因數方法,若是4的倍數但不為100的倍數且又是400的倍數,則該年為閏年。 ```Cin= int str2int(char *date); int IsLeapYear(int year); int dayOfYear(char * date){ int YY = 0, MM = 0, DD = 0, ans = 0; DD = str2int(date+8); MM = str2int(date+5); YY = str2int(date); for(int i = 1; i < MM; i++){ if(i < 8){ if(i==2){ if(IsLeapYear(YY)){ans += 29;} else{ans += 28;} } else if(i&1){ans += 31;} else{ans += 30;} } else{ if(i&1){ans += 30;} else{ans += 31;} } } return ans + DD; } int str2int(char *date){ int ans = 0; while(*date >= '0' && *date <= '9'){ ans = ans*10 + (*date - '0'); date++; } return ans; } int IsLeapYear(int year){ int ans = 0; if((year%4==0 && year%100 != 0) || (year%400 == 0)){ ans = 1; } return ans; } ``` ## Link https://leetcode.com/problems/day-of-the-year/ ###### tags: `Leetcode`