Leap Year Check
Problem
A year is a leap year if it is divisible by 4, except for years divisible by 100. But years divisible by 400 are leap years. Read a year and print Leap year or Not a leap year.
Constraints
- 1 <= year <= 9999
Examples
Input
2024
Output
Leap year
Input
1900
Output
Not a leap year
Solutions
The rule has an exception to an exception. We test 400 first, then 4 and not 100. Logical operators join the tests: && / and for both, || / or for either.
/*
* Problem : Check if a year is a leap year.
* Input : One integer year.
* Output : Leap year or Not a leap year.
* Approach: Use the rule: divisible by 4, but not by 100 unless also by 400.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int year = new Scanner(System.in).nextInt();
// Step 1: Years divisible by 400 are leap years. Example: 2000.
// Step 2: Years divisible by 4 but not by 100 are leap years. Example: 2024. But 1900 is not.
boolean isLeap = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
// Step 3: Print the answer.
System.out.println(isLeap ? "Leap year" : "Not a leap year");
}
}
Hints (1)
- Is 1900 a leap year? And 2000?