878877. Leap Year
Easy
Leap Year
Summary
A leap year is a year that has 366 days instead of the usual 365 days. This happens because it takes the Earth approximately 365.24 days to orbit around the Sun, so an extra day is added to the calendar every four years to keep our seasons in line with the solar year. The problem is to determine whether a given year is a leap year or not.
Detailed Explanation
To solve this problem, we need to write a program that determines whether a given year is a leap year or not. A year is considered a leap year if it is divisible by 4, except for years that are evenly divisible by 100, unless they are also divisible by 400.
Here's the step-by-step breakdown of the solution:
- Start by checking if the year is divisible by 4.
- If it is, then check if it is also divisible by 100.
- If it is not divisible by 100, then it is a leap year.
- If it is divisible by 100, then check if it is also divisible by 400.
- If it is, then it is a leap year.
Here's an ASCII art diagram illustrating the process:
+----------------+
| Is year div by 4? |
+----------------+
yes
+----------------+
| Is year not div by 100? |
+----------------+
yes no
+----------------+
| Year is a leap year! |
| (or) |
| Is year div by 400? |
+----------------+
yes no
+----------------+
| Year is NOT a leap year. |
+----------------+
Time complexity: O(1) Space complexity: O(1)
Optimized Solutions
Java
public boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}