Coding problem · Easy · Basics
Leap Year
Easy Algorithms & data structures
Return true if year is a leap year:
- divisible by 4,
- except years divisible by 100, which are not leap years,
- except years divisible by 400, which are leap years.
Example 1
Input: year = 2024 Output: true
Example 2
Input: year = 1900 Output: false
Example 3
Input: year = 2000 Output: true
Hints
Hint 1
Combine the rules with && and ||: divisible by 4 and (not by 100, or by 400).
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(1) · Space O(1)
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0). 1900 fails the century rule; 2000 is rescued by the 400 rule.
Reference solution
function isLeapYear(year) {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function isLeapYear(year: number): boolean {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
def is_leap_year(year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
<?php
function isLeapYear(int $year): bool
{
return $year % 4 === 0 && ($year % 100 !== 0 || $year % 400 === 0);
}
class Solution {
public boolean isLeapYear(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy