Number of Days in a Month

easy math leap year

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.

Inputyear = 2024, month = 2
Output29
2024 is divisible by 4 and not by 100, so it is a leap year — February has 29 days.

def 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];
}
Time: O(1) Space: O(1)