LeetCode 1154:一年中的第几天(Day of the Year)解法汇总

文章目录

  • Solution

更多LeetCode题解

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.

Solution

class Solution {
public:
    int ordinalOfDate(string date) {
        int year = 1000*(date[0]-'0')+100*(date[1]-'0')+10*(date[2]-'0')+(date[3]-'0');
        int month = 10*(date[5]-'0')+(date[6]-'0');
        int day = 10*(date[8]-'0')+(date[9]-'0');
        int order = 30*(month-1)+day;
        int extra = isRun(year);
        if(month==2){
            return order+1;
        } else if(month==3){
            return order-1+extra;
        }else if(month==4||month==5){
            return order+extra;
        }else if(month==6||month==7){
            return order+1+extra;
        }else if(month==8){
            return order+2+extra;
        }else if(month==9||month==10){
            return order+3+extra;
        }else if(month==11||month==12){
        return order+4+extra;
        }else{
            return order;
        }
    }
    int isRun(int month){
        if(month%100==0){
            if(month%400==0){
                return 1;
            }
        }
        else{
            if(month%4==0){
                return 1;
            }
        }
        return 0;
    }
};

你可能感兴趣的:(LeetCode刷题题解记录)