Skip to main content
Back to problems
#1154
Easy Algorithms

Day of the year

Math String
49.6% acceptance
Feb 25, 2026
506
495
Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn day_of_year(date: String) -> i32 {
    let parts: Vec<i32> = date.split('-').map(|s| s.parse().unwrap()).collect();
    let (year, month, day) = (parts[0], parts[1], parts[2]);
    let days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    let leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    let mut result = day;
    for m in 1..month {
      result += days_in_month[m as usize];
      if m == 2 && leap { result += 1; }
    }
    result
  }
}