Day of the Year

Let’s write a function to calculate the day number of the given year for a date formatted as “YYYY-MM-DD”.

Here’s a step-by-step guide:

  1. Split the date string into the year, month, and day components.
  2. Create a list containing the number of days in each month. For a leap year, adjust the number of days in February to 29.
  3. Calculate the total days by summing the days in the previous months and adding the current day.
  4. Return the total number of days.

A year is a leap year if it’s divisible by 400, or divisible by 4 and not divisible by 100.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def dayOfYear(self, date: str) -> int:
        year, month, day = map(int, date.split('-'))

        # Days in each month, with February as 28
        months_days = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

        # If it's a leap year, set February to 29 days
        if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
            months_days[2] = 29

        # Sum the number of days in the previous months and add the current day
        total_days = sum(months_days[:month]) + day

        return total_days

Explanation:

  • First, we split the date into year, month, and day.
  • We define the number of days in each month, considering February as 28 days initially.
  • If the year is a leap year, we update February’s days to 29.
  • Finally, we calculate the total days by summing up the days of the previous months and adding the current day, and return this value.