Welcome to Subscribe On Youtube
Formatted question description: https://leetcode.ca/all/1118.html
1118. Number of Days in a Month
Level
Easy
Description
Given a year Y
and a month M
, return how many days there are in that month.
Example 1:
Input: Y = 1992, M = 7
Output: 31
Example 2:
Input: Y = 2000, M = 2
Output: 29
Example 3:
Input: Y = 1900, M = 2
Output: 28
Note:
1583 <= Y <= 2100
1 <= M <= 12
Solution
If M
is 1, 3, 5, 7, 8, 10, or 12, then there are 31 days in that month.
If M
is 4, 6, 9, or 11, then there are 30 days in that month.
If M
is 2, then Y
needs to be checked whether it is a leap year. If Y
is divisible by 4 but not divisible by 100, or Y
is divisible by 400, then it is a leap year. There are 29 days in that month if it is a leap year or 28 days in that month otherwise.
-
class Solution { public int numberOfDays(int Y, int M) { if (M == 1 || M == 3 || M == 5 || M == 7 || M == 8 || M == 10 || M == 12) return 31; else if (M == 4 || M == 6 || M == 9 || M == 11) return 30; else { if (Y % 4 == 0 && Y % 100 != 0 || Y % 400 == 0) return 29; else return 28; } } }
-
// OJ: https://leetcode.com/problems/number-of-days-in-a-month/ // Time: O(1) // Space: O(1) class Solution { bool isLeapYear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } public: int numberOfDays(int year, int month) { if (month == 2) return isLeapYear(year) ? 29 : 28; return month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ? 31 : 30; } };
-
class Solution: def numberOfDays(self, year: int, month: int) -> int: leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) days = [0, 31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] return days[month]
-
func numberOfDays(year int, month int) int { leap := (year%4 == 0 && year%100 != 0) || (year%400 == 0) x := 28 if leap { x = 29 } days := []int{0, 31, x, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} return days[month] }
-
function numberOfDays(year: number, month: number): number { const leap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; const days = [ 0, 31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, ]; return days[month]; }