C++     Easy     Math     String    

Problem Statement:

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

 

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 31th, 2019.

Solution:

Make sure to take care of leap year rule. Examples of leap years: 1992,1996,2000,2004,..,2096,2104

Code

 
class Solution {
public:
    int dayOfYear(string date) {
        int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
        int Y=stoi(date.substr(0,4)), M=stoi(date.substr(5,2)), D=stoi(date.substr(8,2));
        if ((Y%4==0 && Y%100>0) || (Y%400==0)) days[1]=29;
        int ctr=0;
        for (int m=0;m<M-1;m++) ctr+=days[m];
        ctr+=D;
        return ctr;
    }
};