A leap year happens every four years, so it's a year that is perfectly divisible by four.
However, if the year is a multiple of 100 (1800, 1900, etc), the year must be divisible by 400 to be leap.
Write a function that determines if the year
is a leap year or not.
Examples:
leapYear(2020) ➞ true leapYear(2021) ➞ false leapYear(1968) ➞ true leapYear(1900) ➞ false
The core challenge of this problem is to correctly identify leap years based on the given rules. Leap years are significant in calendar calculations, date validations, and time-based algorithms. A common pitfall is to only check if a year is divisible by 4, without considering the additional rules for years divisible by 100 and 400.
To solve this problem, we need to follow these steps:
This approach ensures that all the rules for determining a leap year are correctly applied.
Here is a step-by-step breakdown of the algorithm:
// Function to determine if a year is a leap year
function leapYear(year) {
// Check if the year is divisible by 400
if (year % 400 === 0) {
return true;
}
// Check if the year is divisible by 100
if (year % 100 === 0) {
return false;
}
// Check if the year is divisible by 4
if (year % 4 === 0) {
return true;
}
// If none of the above conditions are met, it is not a leap year
return false;
}
// Test cases
console.log(leapYear(2020)); // true
console.log(leapYear(2021)); // false
console.log(leapYear(1968)); // true
console.log(leapYear(1900)); // false
The time complexity of this solution is O(1) because the number of operations does not depend on the input size. The space complexity is also O(1) as we are not using any additional data structures.
Potential edge cases include:
These edge cases are handled by the conditions in our algorithm.
To test the solution comprehensively, we can use a variety of test cases:
We can use JavaScript's built-in console.log function to print the results and verify the correctness of our function.
When approaching such problems, it is essential to:
Practicing similar problems and studying algorithms can help improve problem-solving skills.
In this blog post, we discussed how to determine if a year is a leap year using a simple algorithm. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong problem-solving skills in programming.
For further reading and practice, consider the following resources: