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 systems and are used to keep our calendar year synchronized with the astronomical year. Misidentifying a leap year can lead to incorrect date calculations.
Common pitfalls include not accounting for the special rule regarding years that are multiples of 100 but not 400.
To solve this problem, we need to check the divisibility of the given year by 4, 100, and 400. Here's a step-by-step approach:
Here is a step-by-step breakdown of the algorithm:
def leapYear(year):
# Check if the year is divisible by 4
if year % 4 == 0:
# Check if the year is divisible by 100
if year % 100 == 0:
# Check if the year is divisible by 400
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
# Test cases
print(leapYear(2020)) # ➞ true
print(leapYear(2021)) # ➞ false
print(leapYear(1968)) # ➞ true
print(leapYear(1900)) # ➞ false
The time complexity of this solution is O(1) because the number of operations does not depend on the size of the input. The space complexity is also O(1) as we are not using any additional space that scales with the input.
Potential edge cases include:
These edge cases are handled by the algorithm as it checks for divisibility by 4, 100, and 400 in the correct order.
To test the solution comprehensively, we should include a variety of test cases:
We can use Python's built-in unittest
framework to automate these tests.
When approaching such problems, it is crucial to:
Practicing similar problems and studying algorithms can significantly improve problem-solving skills.
In this blog post, we discussed how to determine if a given year is a leap year. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is essential for developing strong problem-solving skills in programming.
We encourage readers to practice and explore further to solidify their understanding.