1154. Day of the Year Easy
1/**
2 * [1154] Day of the Year
3 *
4 * Given a string date representing a <a href="https://en.wikipedia.org/wiki/Gregorian_calendar" target="_blank">Gregorian calendar</a> date formatted as YYYY-MM-DD, return the day number of the year.
5 *
6 * Example 1:
7 *
8 * Input: date = "2019-01-09"
9 * Output: 9
10 * Explanation: Given date is the 9th day of the year in 2019.
11 *
12 * Example 2:
13 *
14 * Input: date = "2019-02-10"
15 * Output: 41
16 *
17 *
18 * Constraints:
19 *
20 * date.length == 10
21 * date[4] == date[7] == '-', and all other date[i]'s are digits
22 * date represents a calendar date between Jan 1^st, 1900 and Dec 31^th, 2019.
23 *
24 */
25pub struct Solution {}
26
27// problem: https://leetcode.com/problems/day-of-the-year/
28// discuss: https://leetcode.com/problems/day-of-the-year/discuss/?currentPage=1&orderBy=most_votes&query=
29
30// submission codes start here
31
32impl Solution {
33 const DATA: [i32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
34 pub fn day_of_year(date: String) -> i32 {
35 let leap_year = |y: i32| -> bool {
36 if y % 100 == 0 {
37 return y % 400 == 0;
38 } else {
39 return y % 4 == 0;
40 }
41 };
42
43 let mut parts = date.split('-');
44 let year: i32 = match parts.next() {
45 Some(x) => x.parse::<i32>().unwrap(),
46 None => 0,
47 };
48 let month: i32 = match parts.next() {
49 Some(x) => x.parse::<i32>().unwrap(),
50 None => 0,
51 };
52 let day: i32 = match parts.next() {
53 Some(x) => x.parse::<i32>().unwrap(),
54 None => 0,
55 };
56 let mut result = 0;
57 for i in 0..month - 1 {
58 result += Self::DATA[i as usize];
59 }
60 if month > 2 && leap_year(year) {
61 result += 1;
62 }
63 day + result
64 }
65}
66
67// submission codes end
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn test_1154() {
75 assert_eq!(Solution::day_of_year("2019-02-10".to_owned()), 41);
76 assert_eq!(Solution::day_of_year("2019-01-09".to_owned()), 9);
77 assert_eq!(Solution::day_of_year("2019-10-21".to_owned()), 294);
78 assert_eq!(Solution::day_of_year("2000-10-21".to_owned()), 295);
79 assert_eq!(Solution::day_of_year("2020-10-21".to_owned()), 295);
80 }
81}
82
Back
© 2025 bowen.ge All Rights Reserved.