def numberOfDays(year: int, month: int) -> int:
# February: check for leap year
if month == 2:
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return 29
else:
return 28
# Months with 31 days
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
# Months with 30 days
return 30
class Solution {
public:
int numberOfDays(int year, int month) {
if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return 29;
else
return 28;
}
if (month == 1 || month == 3 || month == 5 || month == 7 ||
month == 8 || month == 10 || month == 12)
return 31;
return 30;
}
};
class Solution {
public int numberOfDays(int year, int month) {
if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return 29;
else
return 28;
}
if (month == 1 || month == 3 || month == 5 || month == 7 ||
month == 8 || month == 10 || month == 12)
return 31;
return 30;
}
}
function numberOfDays(year, month) {
if (month === 2) {
if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
return 29;
} else {
return 28;
}
}
if ([1, 3, 5, 7, 8, 10, 12].includes(month)) {
return 31;
}
return 30;
}
Given two integers, year
and month
, return the number of days in that month for the specified year. For example, February has either 28 or 29 days depending on whether the year is a leap year. The input values are guaranteed to represent a valid year and month (1 ≤ month
≤ 12, year
≥ 1).
Key constraints:
The problem asks us to determine how many days are in a given month, considering leap years for February. At first glance, you might think of using a big set of if-else statements for each month, but that would be repetitive and hard to maintain. Instead, we can use the known rules of the Gregorian calendar:
By focusing on these rules, we can quickly map each month to its day count, with a special case for February.
month
is February (i.e., month == 2
).year
is a leap year:
This approach is efficient because it uses simple conditionals and requires no loops or complex data structures. The leap year check is performed only if necessary.
Let's take an example: year = 2024
, month = 2
.
month == 2
. It is, so we proceed to the leap year check.2024 % 4 == 0
), and not by 100 (2024 % 100 != 0
), so it is a leap year.
Another example: year = 2023
, month = 11
.
month == 2
. It's not, so we check if 11 is in the set of months with 31 days. It's not.The efficiency comes from mapping months directly to their day counts and only checking leap years when necessary.
To solve the "Number of Days in a Month" problem, we leveraged the rules of the Gregorian calendar and handled February as a special case with a leap year check. All other months have a fixed number of days. The solution is concise, fast, and easy to maintain, making it both elegant and practical for real-world use.