Number of Days in a Month
Problem
Given a year and a month, return the number of days in that month. February has 29 days in a leap year and 28 otherwise. A year is a leap year if it is divisible by 4 but not by 100, or if it is divisible by 400.
year = 2024, month = 229def number_of_days(year, month):
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
if month == 2 and leap:
return 29
return days[month - 1]
function numberOfDays(year, month) {
const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const leap = (year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0);
if (month === 2 && leap) return 29;
return days[month - 1];
}
class Solution {
public int numberOfDays(int year, int month) {
int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
boolean leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (month == 2 && leap) return 29;
return days[month - 1];
}
}
int numberOfDays(int year, int month) {
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (month == 2 && leap) return 29;
return days[month - 1];
}
Explanation
Almost every month has a fixed length, so we just look it up in a table. The only twist is February, which has 29 days in a leap year and 28 otherwise.
We keep an array days holding the standard day counts for the 12 months, with February stored as 28. For any month we simply return days[month - 1] (subtracting 1 because the array is 0-indexed).
Before that lookup, we test for a leap year using the calendar rule: a year is leap if it is divisible by 4 and not by 100, or if it is divisible by 400. In code that is (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0). If the month is February and the year is leap, we return 29 instead of the table value.
Example: year = 2024, month = 2. Since 2024 is divisible by 4 and not by 100, it is a leap year, so February returns 29. For year = 1900, it is divisible by 100 but not 400, so February is just 28.
Every operation is a couple of comparisons and one array access, so this is constant time and space.