Number of Days in a Month

Here is a Python solution using built-in Python libraries. It calculates the number of days in a given month by utilizing the datetime and calendar modules.

1
2
3
4
5
import calendar

class Solution:
    def numberOfDays(self, year: int, month: int) -> int:
        return calendar.monthrange(year, month)[1]

The function calendar.monthrange(year, month) returns a tuple containing two integers. The first value is the day of the week that the specified month begins on (0 for Monday, 1 for Tuesday, etc.), and the second value is the number of days in the month. Therefore, [1] returns the second value, which is the number of days in the month.

This function handles leap years automatically, so you don’t have to manually check for them.