JuniorCodeCommonNot answered yet
Determine if a year is a leap year
Return true if year is a leap year under the Gregorian calendar rules.
Requirements:
divisible by 400. So 2000 → true, 1900 → false, 2024 → true.
- Divisible by 4, EXCEPT century years (divisible by 100), UNLESS also
- Express it as a single boolean expression, not nested
ifstatements. - Do not use
std::chrono::year::is_leap().
bool isLeapYear(int year) {
// your code here
}
Write the implementation.
A year is a leap year if: divisible by 4, EXCEPT centuries (divisible by 100), UNLESS also divisible by 400. So 2000 is a leap year, 1900 is not, 2024 is. Implement with the standard three-condition check.
- ✗Checking only
year % 4 == 0and forgetting the century exception - ✗Writing nested ifs that make the logic hard to read instead of one boolean expression
- ✗Not handling year 0 or negative years if the API accepts them
- →What is the Gregorian calendar rule and why was it introduced?
- →How does
std::chrono::year::is_leap()work in C++20?
Contents
Task
Write a function to determine if a year is a leap year using the Gregorian calendar rules.
Solution
constexpr bool isLeapYear(int year) {
return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0);
}
Key points
- Three rules in one expression: divisible by 4, except centuries, unless divisible by 400.
- Mark
constexprso it can be evaluated at compile time. - C++20:
std::chrono::year{y}.is_leap()is the idiomatic solution.
Contents