列表

详情


1118. 一月有多少天

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

 

示例 1:

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

示例 2:

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

示例 3:

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

 

提示:

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
class Solution { public: int numberOfDays(int year, int month) { } };

java 解法, 执行用时: 0 ms, 内存消耗: 38 MB, 提交时间: 2023-10-15 15:31:56

class Solution {
    public int numberOfDays(int Y, int M) {
        int[] year1 = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 闰年
        int[] year2 = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 非闰年
        if((Y % 100 != 0 && Y % 4 == 0) || Y % 400 == 0) {
            return year1[M-1];
        }
        return year2[M-1];
    }
}

cpp 解法, 执行用时: 0 ms, 内存消耗: 6.4 MB, 提交时间: 2023-10-15 15:31:45

class Solution {
public:
    int numberOfDays(int Y, int M) {
        int year[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        if (M == 2 && Y % 4 == 0 && (Y % 100 != 0 || Y % 400 == 0)) // 闰二月
            return 29;
        else
            return year[M - 1];
    }
};

golang 解法, 执行用时: 4 ms, 内存消耗: 1.8 MB, 提交时间: 2023-10-15 15:31:33

func numberOfDays(Y int, M int) int {
    // 把时间先加到下个月的第一天,再减掉一天就是本月的最后一天了
    return time.Date(Y, time.Month(M+1), 1, 0, 0, 0, 0, time.Local).AddDate(0, 0, -1).Day()
}

func numberOfDays2(Y int, M int) int {
    year1 := []int{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} // 闰年
    year2 := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} // 非闰年
    if (Y % 100 != 0 && Y % 4 == 0) || Y % 400 == 0 {
        return year1[M-1];
    }
    return year2[M-1];
}

python3 解法, 执行用时: 40 ms, 内存消耗: 16 MB, 提交时间: 2023-10-15 15:31:12

class Solution:
    def numberOfDays(self, Y: int, M: int) -> int:
        if (Y % 100 != 0 and Y % 4 == 0) or Y % 400 == 0:
            return [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][M - 1] # 闰年
        else:
            return [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][M - 1] # 非闰年

上一题