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 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
Constraints:
- date.length == 10
date[4] == date[7] == '-', and all otherdate[i]’s are digitsdaterepresents a calendar date between Jan 1st, 1900 and Dec 31st, 2019.
💡 Hint 1:
Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one).
Submitted Code
class Solution:
def dayOfYear(self, date: str) -> int:
year, month, day = map(int, date.split("-"))
feb_days = 29 if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0) else 28
month_days = [31, feb_days, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return sum(month_days[:month-1]) + day
Runtime: 13 ms | Beats 42.16%
Memory: 17.13 MB | Beats 99.72%
그레고리력 윤년 계산 규칙
- 연도가 4의 배수이면 윤년 후보이다.
- 윤년 후보 중 100의 배수는 제외된다.
- 100의 배수더라도 400의 배수이면 윤년이다.
Other Solutions
1st
class Solution:
def dayOfYear(self, date: str) -> int:
# we first make a list of days in a year when a specific
# month ends
list_year=[0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
day=int(date[-2:])
year=int(date[:4])
month=int(date[5:7])
# if year is leap and february is gone, add an extra day
if year%4==0 and year!=1900 and month>2 :
day+=1
#return days of specific month + date
return list_year[month-1]+day
time complexity: 𝑂(1)
space complexity: 𝑂(1)
월별 누적 일수를 미리 적어놓는 방법도 있다.
2nd
class Solution:
def ordinalOfDate(self, date):
Y, M, D = map(int, date.split('-'))
return int((datetime.datetime(Y, M, D) - datetime.datetime(Y, 1, 1)).days + 1)
문자열을 datetime 타입으로 변경하면 월별 일수를 몰라도 자동으로 계산할 수 있다.