Skip to content

Latest commit

 

History

History
106 lines (75 loc) · 2.22 KB

File metadata and controls

106 lines (75 loc) · 2.22 KB

English Version

题目描述

指定年份 Y 和月份 M,请你帮忙计算出该月一共有多少天。

 

示例 1:

输入:Y = 1992, M = 7
输出:31

示例 2:

输入:Y = 2000, M = 2
输出:29

示例 3:

输入:Y = 1900, M = 2
输出:28

 

提示:

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

解法

Python3

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]

Java

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];
    }
}

C++

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];
    }
};

Go

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]
}

...