Find the number of days in a month
Return the number of days in a Gregorian calendar month for a given year, including leap-year February.
Course progress
Problem 67 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
year = 2024; month = 2
Expected output
29
What is happening?
2024 is divisible by 4 and not by 100, so it is a leap year. February therefore has 29 days.
Solution strategy
Build the right mental model
Validate the month, handle February with the leap-year rule, and use the fixed 30-day month set for the remaining cases.
Core concepts
conditions · calendar arithmetic
Complexity
Time O(1), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for days-in-month
using System;
class Program
{
static bool IsLeapYear(int year)
{
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
}
static int DaysInMonth(int year, int month)
{
if (month < 1 || month > 12) throw new ArgumentOutOfRangeException("month");
if (month == 2) return IsLeapYear(year) ? 29 : 28;
return month == 4 || month == 6 || month == 9 || month == 11 ? 30 : 31;
}
static void Main()
{
Console.WriteLine(DaysInMonth(2024, 2));
}
}Knowledge check
Questions students often ask
What is the main idea behind find the number of days in a month?
Validate the month, handle February with the leap-year rule, and use the fixed 30-day month set for the remaining cases.
What is the time and space complexity of this solution?
Time O(1), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.