跳转至

1118. 一月有多少天 🔒

题目描述

指定年份 year 和月份 month,返回 该月天数 

 

示例 1:

输入:year = 1992, month = 7
输出:31

示例 2:

输入:year = 2000, month = 2
输出:29

示例 3:

输入:year = 1900, month = 2
输出:28

 

提示:

  • 1583 <= year <= 2100
  • 1 <= month <= 12

解法

方法一:判断闰年

我们可以先判断给定的年份是否为闰年,如果年份能被 $4$ 整除但不能被 $100$ 整除,或者能被 $400$ 整除,那么这一年就是闰年。

闰年的二月有 $29$ 天,平年的二月有 $28$ 天。

我们可以用一个数组 $days$ 存储当前年份每个月的天数,其中 $days[0]=0$,$days[i]$ 表示当前年份第 $i$ 个月的天数。那么答案就是 $days[month]$。

时间复杂度 $O(1)$,空间复杂度 $O(1)$。

1
2
3
4
5
class Solution:
    def numberOfDays(self, year: int, month: int) -> int:
        leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
        days = [0, 31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        return days[month]
1
2
3
4
5
6
7
class Solution {
    public int numberOfDays(int year, int month) {
        boolean leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        int[] days = new int[] {0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        return days[month];
    }
}
1
2
3
4
5
6
7
8
class Solution {
public:
    int numberOfDays(int year, int month) {
        bool leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
        vector<int> days = {0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        return days[month];
    }
};
1
2
3
4
5
6
7
8
9
func numberOfDays(year int, month int) int {
    leap := (year%4 == 0 && year%100 != 0) || (year%400 == 0)
    x := 28
    if leap {
        x = 29
    }
    days := []int{0, 31, x, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    return days[month]
}
1
2
3
4
5
function numberOfDays(year: number, month: number): number {
    const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
    const days = [0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    return days[month];
}

评论