LeetCode the first few days of 1154. year

Give you a date string representing the date by YYYY-MM-DD format, and you calculate the return date is the first few days of the year.

Under normal circumstances, we believe that January 1 is the first day of the year, January 2 is the first two days every year, and so on. The number of days in each month of the year is consistent with the current chronology (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

Ideas: first determine the month, the number of days of the month preceding the current month and add up, together with the date of the current month is the number of days, and then eradicate leap determine the number of days in February.

Month and when added, may be in reverse order of the number of days in the months of the year are arranged in an array, find the corresponding month, and add sequentially, February 28 days, and then determines whether to raise a leap years.

class Solution {
 public :
     int calcOfDay ( int year, int month The, int Day) {
         int Mon [ 12 is ] = { 30 , 31 is , 30 , 31 is , 31 is , 30 , 31 is , 30 , 31 is , 28 , 31 is , 0 }; // date arranged in reverse order from November, December, day of the month together like
         int RES = 0 ;
         for ( int I = 12 is -month; I <12 is ; I ++ ) 
            RES + = [I] Mon;
         IF ((month The> 2 ) && ((% year . 4 == 0 && year% 100 ! = 0 ) || year% 400 == 0 )) // if more than month is a leap year and month, a date plus 
            RES ++ ; 
        RES + = Day;
         return RES; 
    } 
    
    int dayOfYear ( String dATE) {
        int year, month The, Day;
         String years date.substr = ( 0 , . 4 );
        string months = date.substr(5, 2);
        string days = date.substr(8, 2);
        stringstream ss;
        ss << years;
        ss >> year;
        ss.clear();
        ss << months;
        ss >> month;
        ss.clear();
        ss << days;
        ss >> day;
        int res = calcOfDay(year, month, day);
        return res;
    }
};

 The use of string substr sbustr (int index, int len); taken from the index of the starting position length len of the string.

Guess you like

Origin www.cnblogs.com/hhhhan1025/p/11521321.html