Skip to content

1118. Number of Days in a Month πŸ”’

Description

Given a year year and a month month, return the number of days of that month.

 

Example 1:

Input: year = 1992, month = 7
Output: 31

Example 2:

Input: year = 2000, month = 2
Output: 29

Example 3:

Input: year = 1900, month = 2
Output: 28

 

Constraints:

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

Solutions

Solution 1: Determine Leap Year

We can first determine whether the given year is a leap year. If the year can be divided by $4$ but not by $100$, or can be divided by $400$, then this year is a leap year.

February has $29$ days in a leap year and $28$ days in a common year.

We can use an array $days$ to store the number of days in each month of the current year, where $days[0]=0$, $days[i]$ represents the number of days in the $i$th month of the current year. Then the answer is $days[month]$.

The time complexity is $O(1)$, and the space complexity is $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];
}

Comments