Skip to content

Latest commit

 

History

History
110 lines (74 loc) · 2.33 KB

File metadata and controls

110 lines (74 loc) · 2.33 KB

中文文档

Description

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

Solutions

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

...