Formatted question description: https://leetcode.ca/all/1154.html

1154. Day of the Year (Easy)

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

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] == '-', and all other date[i]'s are digits
  • date represents a calendar date between Jan 1st, 1900 and Dec 31, 2019.

Related Topics:
Math

Solution 1.

// OJ: https://leetcode.com/problems/day-of-the-year/

// Time: O(1)
// Space: O(1)
class Solution {
    const int days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    bool isLeap(int y) {
        return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
    }
public:
    int dayOfYear(string date) {
        int y = stoi(date.substr(0, 4)), m = stoi(date.substr(5, 2)), d = stoi(date.substr(8));
        return (m > 2 && isLeap(y)) + accumulate(begin(days), begin(days) + m - 1, 0) + d;
    }
};

Java

class Solution {
    public int dayOfYear(String date) {
        String[] array = date.split("-");
        int year = Integer.parseInt(array[0]), month = Integer.parseInt(array[1]), day = Integer.parseInt(array[2]);
        if (month == 1)
            return day;
        if (month == 2)
            return 31 + day;
        int leap = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? 1 : 0;
        int dayOfYear = 31 + 28 + leap;
        if (month > 3)
            dayOfYear += 31;
        if (month > 4)
            dayOfYear += 30;
        if (month > 5)
            dayOfYear += 31;
        if (month > 6)
            dayOfYear += 30;
        if (month > 7)
            dayOfYear += 31;
        if (month > 8)
            dayOfYear += 31;
        if (month > 9)
            dayOfYear += 30;
        if (month > 10)
            dayOfYear += 31;
        if (month > 11)
            dayOfYear += 30;
        dayOfYear += day;
        return dayOfYear;
    }
}

All Problems

All Solutions