↓ Skip to main content
LeetCode 1154: Day of the Year

LeetCode 1154: Day of the Year

·209 words·1 min· loading · loading ·
Author
Dawn Magnet
Tech enthusiast & daily solver.

Given a string date representing a date in the YYYY-MM-DD format under the Common Era, calculate and return the ordinal day of that date within its year.

Normally, January 1 is the first day of every year, January 2 is the second day, and so on. The number of days in each month follows the Gregorian calendar.

 

Example 1:

Input:date = "2019-01-09"
Output:9

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] == '-'; all other date[i] are digits
  • date ranges from January 1, 1900, to December 31, 2019

Analysis
#

Split the date, determine whether the year is a leap year, and then sum the days.

Code (Rust)
#

impl Solution {
    pub fn day_of_year(date: String) -> i32 {
        let v: Vec<i32> = date.split('-').map(|x| x.parse().unwrap()).collect();
        let mut days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        if v[1] > 2 && v[0] % 4 == 0 && (v[0] % 100 != 0 || v[0] % 400 == 0) {
            days[1] += 1;
        }
        &days[0..(v[1] as usize - 1)].iter().sum() + v[2]
    }
}

Code (Go)
#

func dayOfYear(date string) int {
    t, _ := time.Parse("2006-01-02", date)
    return t.YearDay()
}