Problem#
Given a year year
and a month month
, return the number of days of that month .
Examples#
Example 1:
1
2
Input: year = 1992 , month = 7
Output: 31
Example 2:
1
2
Input: year = 2000 , month = 2
Output: 29
Example 3:
1
2
Input: year = 1900 , month = 2
Output: 28
Constraints:
1583 <= year <= 2100
1 <= month <= 12
Solution#
Method 1 – Simple Lookup and Leap Year Check#
Intuition#
Months have a fixed number of days except February, which depends on whether the year is a leap year. Leap years are divisible by 4, but not by 100 unless also by 400.
Approach#
Use an array to store days for each month.
For February, check if the year is a leap year and return 29 or 28.
For other months, return the value from the array.
Code#
Cpp
Go
Java
Kotlin
Python
Rust
Typescript
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public :
int numberOfDays(int year, int month) {
if (month == 2 ) {
if ((year% 4 == 0 && year% 100 != 0 ) || year% 400 == 0 ) return 29 ;
return 28 ;
}
int days[] = {31 ,28 ,31 ,30 ,31 ,30 ,31 ,31 ,30 ,31 ,30 ,31 };
return days[month- 1 ];
}
};
1
2
3
4
5
6
7
8
func numberOfDays (year , month int ) int {
if month == 2 {
if (year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 { return 29 }
return 28
}
days := []int {31 ,28 ,31 ,30 ,31 ,30 ,31 ,31 ,30 ,31 ,30 ,31 }
return days [month - 1 ]
}
1
2
3
4
5
6
7
8
9
10
class Solution {
public int numberOfDays (int year, int month) {
if (month == 2) {
if ((year% 4== 0 && year% 100!= 0) || year% 400== 0) return 29;
return 28;
}
int [] days = {31,28,31,30,31,30,31,31,30,31,30,31};
return days[ month- 1] ;
}
}
1
2
3
4
5
6
7
8
9
10
class Solution {
fun numberOfDays (year: Int, month: Int): Int {
if (month == 2 ) {
if ((year%4 == 0 && year%100 != 0 ) || year%400 == 0 ) return 29
return 28
}
val days = arrayOf(31 ,28 ,31 ,30 ,31 ,30 ,31 ,31 ,30 ,31 ,30 ,31 )
return days[month-1 ]
}
}
1
2
3
4
5
6
7
8
class Solution :
def numberOfDays (self, year: int, month: int) -> int:
if month == 2 :
if (year% 4 == 0 and year% 100 != 0 ) or year% 400 == 0 :
return 29
return 28
days = [31 ,28 ,31 ,30 ,31 ,30 ,31 ,31 ,30 ,31 ,30 ,31 ]
return days[month- 1 ]
1
2
3
4
5
6
7
8
9
10
impl Solution {
pub fn number_of_days (year: i32 , month: i32 ) -> i32 {
if month == 2 {
if (year% 4 == 0 && year% 100 != 0 ) || year% 400 == 0 { return 29 ; }
return 28 ;
}
let days = [31 ,28 ,31 ,30 ,31 ,30 ,31 ,31 ,30 ,31 ,30 ,31 ];
days[(month- 1 ) as usize ]
}
}
1
2
3
4
5
6
7
8
function numberOfDays (year : number , month : number ): number {
if (month === 2 ) {
if ((year % 4 === 0 && year % 100 !== 0 ) || year % 400 === 0 ) return 29 ;
return 28 ;
}
const days = [31 ,28 ,31 ,30 ,31 ,30 ,31 ,31 ,30 ,31 ,30 ,31 ];
return days [month - 1 ];
}
Complexity#
⏰ Time complexity: O(1)
🧺 Space complexity: O(1)