Check Whether a Year Is a Leap Year
Solve this ProblemEasy10 min
Topics
BasicsConditionalsMath
Companies
TCSInfosysWipro
Given an integer
year, return whether it is a leap year.
A year is a leap year if it's divisible by 4, except century years (divisible by 100) — those are leap years only if they're also divisible by 400. (2024 is a leap year; 1900 is not; 2000 is.)
The step-by-stepStep-by-Step ChecksAn if/else-if/else chain that applies the three divisibility rules one at a time, in the order that lets each one short-circuit the rest. version mirrors exactly how the rule is usually explained out loud. The single expressionSingle Boolean ExpressionCombining AND/OR directly: (div by 4 AND NOT a century year) OR (div by 400) — both ways to be a leap year, joined with no branching at all. version folds the same logic into one line using && and ||, relying on short-circuit evaluation to skip unnecessary checks.
Test Case 1:
Input:year = 2024
Output:true
Explanation:2024 is divisible by 4 and isn't a century year — a leap year.
Test Case 2:
Input:year = 1900
Output:false
Explanation:1900 is divisible by 100 but not by 400 — century years need that stricter check.
Test Case 3:
Input:year = 2000
Output:true
Explanation:2000 is divisible by 100 AND by 400 — a leap year despite being a century year.
Constraints
- ◆
1 ≤ year ≤ 9999
Try the Dry Run
Approach & Solutions
Step-by-Step Divisibility ChecksGood
Apply the leap year rule one condition at a time. A year that isn't divisible by 4 is never a leap year — stop immediately. Otherwise, if it isn't a century year (not divisible by 100), it's automatically a leap year. Only century years need the stricter final check: they're a leap year only if also divisible by 400.
Time
O(1)Space
O(1)Java
1class Solution {
2 public boolean isLeapYear(int year) {
3 if (year % 4 != 0) {
4 return false;
5 } else if (year % 100 != 0) {
6 return true;
7 } else {
8 return year % 400 == 0;
9 }
10 }
11}Single Boolean ExpressionOptimal
The exact same rule, combined into one expression: a year is a leap year if (divisible by 4 AND not a century year) OR (divisible by 400). Both sides of the OR independently cover one of the two ways to be a leap year, so no branching is needed at all.
Time
O(1)Space
O(1)Java
1class Solution {
2 public boolean isLeapYear(int year) {
3 return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
4 }
5}