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:

  1. 1583 <= Y <= 2100
  2. 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;
        }
    }
}

All Problems

All Solutions