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

题目描述

Given a year Y and a month M, return how many days there are in that month.

Example 1:

Input: Y = 1992, M = 7
Output: 31

Example 2:

Input: Y = 2000, M = 2
Output: 29

Example 3:

Input: Y = 1900, M = 2
Output: 28

Note:

1、 1583<=Y<=2100
2、 1<=M<=12

题目大意

判断给出的某年某月有多少天。

解题方法

判断是否是闰年

这个题和1185. Day of the Weekopen in new window类似。

这个题中计算出当年是不是闰年,然后从数组中读取当月的天数。

C++代码如下:

class Solution {
public:
    int numberOfDays(int Y, int M) {
        return daysOfMonth[isLeapYear(Y)][M - 1];
    }
    bool isLeapYear(int year) {
        return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
    }
    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

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

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