LeetCode 1118: Number of Days in a Month Solution

Master LeetCode problem 1118 (Number of Days in a Month), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1118. Number of Days in a Month

Easy

Problem Explanation

Explanation

To solve this problem, we need to determine the number of days in a given month and year. We can achieve this by considering leap years and non-leap years. For non-leap years, each month has a fixed number of days. For leap years, we need to consider the special case of February having 29 days.

The algorithm involves the following steps:

  1. Check if the given year is a leap year.
  2. Based on the month index, return the number of days in that month accounting for leap years.

Time complexity: O(1) Space complexity: O(1)

Solution Code

class Solution {
    public int numberOfDays(int Y, int M) {
        int[] daysInMonth = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        if (M == 2 && (Y % 4 == 0 && Y % 100 != 0 || Y % 400 == 0)) {
            return 29;
        }
        return daysInMonth[M];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1118 (Number of Days in a Month)?

This page provides optimized solutions for LeetCode problem 1118 (Number of Days in a Month) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1118 (Number of Days in a Month)?

The time complexity for LeetCode 1118 (Number of Days in a Month) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1118 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1118 in Java, C++, or Python.

Back to LeetCode Solutions