题目地址:https://leetcode.com/problems/day-of-the-year/

题目描述

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:

1、 date.length==10
2、 date[4]==date[7]=='-',andallotherdate[i]'saredigits;
3、 daterepresentsacalendardatebetweenJan1st,1900andDec31,2019.;

题目大意

判断给出的日期是当月的第多少天。

解题方法

计算1月1号之间天数

这个题和1185. Day of the Weekopen in new window类似。这个题中计算出当年是不是闰年,然后计算和1月1号之间的天数就行了,需要累加每个月,特别注意二月份。

C++代码如下:

class Solution {
public:
    int dayOfYear(string date) {
        int year = stoi(date.substr(0, 4));
        int month = stoi(date.substr(5, 2));
        int day = stoi(date.substr(8));
        return countDays(day, month, year);
    }
    bool isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }
    int countDays(int day, int month, int year) {
        int res = 0;
        while (month > 1) {
            res += daysOfMonth[isLeapYear(year)][month - 2];
            month--;
        }
        res += day;
        return res;
    }
    int daysOfMonth[2][12] = {
        {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
        {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    };
};

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

2022

DDKK.COM 弟弟快看-教程,程序员编程资料站,版权归原作者所有

本文经作者:负雪明烛 授权发布,任何组织或个人未经作者授权不得转发