# 1360. Number of Days Between Two Dates ###### tags: `leetcode` `1360` `easy` ## :memo: Question ![](https://i.imgur.com/r2m0y0Z.png) ## :memo: 題意 * 給你兩個日期,請你算出兩個日期差了幾天。 ## :memo: leetcode solution * :medal: **思考一**: 那我可以算他從西元0元到他給的日期a與日期b各過了幾天,相減取絕對值。 * :medal: **思考二**: 閏年要怎麼算(我覺得大家最大的問題都會卡在這)。 #### 維基百科 1. 公元年分非4的倍數,為平年。 1. 公元年分為4的倍數但非100的倍數,為閏年。 1. 公元年分為100的倍數但非400的倍數,為平年。 1. 公元年分為400的倍數為閏年。 ## :memo: my solution code ```python= class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: month_day = [31,28,31,30,31,30,31,31,30,31,30,31] leap_month_day = [31,29,31,30,31,30,31,31,30,31,30,31] def countday(year, month, day): count = 0 for i in range(0, year): if leap(i): count += 366 else: count += 365 if leap(year): for i in range(month-1): count += leap_month_day[i] else: for i in range(month-1): count += month_day[i] return count + day def leap(year): if year % 4 == 0: if year % 100 != 0: return True else: if year % 400 != 0: return False else: return True else: return False date1list = date1.split("-") date2list = date2.split("-") count1 = countday(int(date1list[0]), int(date1list[1]), int(date1list[2])) count2 = countday(int(date2list[0]), int(date2list[1]), int(date2list[2])) return abs(count1-count2) ``` ## :memo: BigO * 時間複雜度: O(date1+date2)。 * 空間複雜度: O(1)。