--- tags: LeetCode --- # 1154. Day of the Year Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. 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 Example 3: Input: date = "2003-03-01" Output: 60 Example 4: Input: date = "2004-03-01" Output: 61 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, 2019. 輸入範本如下 ```C# 92 ms 24.1 MB You are here! Your runtime beats 40.91 % of csharp submissions. public class Solution { public int DayOfYear(string date) { } } ``` 自我限制 : 禁止使用 DateTime 相關物件 ```C# 136 ms 24 MB faster than 6.06% of C# online submissions for Day of the Year. public int DayOfYear(string date) { DateTime d = DateTime.Parse(date); return d.DayOfYear; } ``` ```C# 92 ms 24.1 MB You are here! Your runtime beats 40.91 % of csharp submissions. public int DayOfYear(string date) { var dateTime = DateTime.Parse(date); var year = dateTime.Year; var result = 0; while (year == dateTime.Year) { result++; dateTime = dateTime.AddDays(-1); } return result; } ``` ### 直覺想法 先查一下閏年的條件... 1. 年能被 400 整除 2. 年能被 4 整除且不能被 100 整除 - 開一個長度十三的陣列做為表 (索引值 0 處 , 不會用到) , 這樣就可以直接使用月份 , 不需要剪一. 另外表內紀錄的是累加天數 , 而非月份天數 , 因此不需要再將月數相加. 就可以得到該月之前的累加天數. - 使用 Substring 的效能比 Spilt 好 (此題 , 格式固定) ```C# 68 ms 22.8 MB You are here! Your runtime beats 95.45 % of csharp submissions. public int DayOfYear(string date) { var days = new int[] {-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; int year = int.Parse(date.Substring(0, 4)), month = int.Parse(date.Substring(5, 2)), day = int.Parse(date.Substring(8, 2)); int isLeap = month > 2 && ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) ? 1 : 0; return days[month] + day + isLeap; } ``` ### Thank you! You can find me on - [GitHub](https://github.com/s0920832252) - [Facebook](https://www.facebook.com/fourtune.chen) 若有謬誤 , 煩請告知 , 新手發帖請多包涵 # :100: :muscle: :tada: :sheep: