Practice › Basics
Leap Year
Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant
Print YES if the year is a leap year, otherwise NO.
A year is a leap year if it is divisible by 4, except years divisible by 100, which are leap years only if they are also divisible by 400.
Input
A single integer y.
Output
YES or NO.
Constraints
- 1 ≤ y ≤ 10^9
Example 1
Input
2024
Output
YES
Example 2
Input
1900
Output
NO
Hints
- Most years divisible by 4 are leap years — but not all.
- Century years (divisible by 100) are leap years only when divisible by 400.
Approach
Translate the rule directly: (y % 4 == 0 && y % 100 != 0) || y % 400 == 0. Check the 400 case as part of the condition — 2000 was a leap year, 1900 was not.
Complexity: O(1) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long y;
cin >> y;
bool leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
cout << (leap ? "YES" : "NO") << "\n";
return 0;
}Python solution
y = int(input())
print("YES" if (y % 4 == 0 and y % 100 != 0) or y % 400 == 0 else "NO")Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
long y = new Scanner(System.in).nextLong();
boolean leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
System.out.println(leap ? "YES" : "NO");
}
}