#include <iostream>
// Function to determine if a year is a leap year
bool leapYear(int 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's not a leap year
return false;
}
int main() {
// Test cases
std::cout << "2020: " << leapYear(2020) << std::endl; // true
std::cout << "2021: " << leapYear(2021) << std::endl; // false
std::cout << "1968: " << leapYear(1968) << std::endl; // true
std::cout << "1900: " << leapYear(1900) << std::endl; // false
return 0;
}
## Complexity Analysis
### Time Complexity
The time complexity of this solution is O(1) because the number of operations does not depend on the input size.
### Space Complexity
The space complexity is O(1) as we are not using any additional space that grows with the input size.
## Edge Cases
### Identified Edge Cases
- Years that are exactly divisible by 400 (e.g., 2000).
- Years that are exactly divisible by 100 but not 400 (e.g., 1900).
- Years that are exactly divisible by 4 but not 100 (e.g., 2020).
- Years that are not divisible by 4 (e.g., 2021).
### Handling Edge Cases
The algorithm handles these edge cases by checking the conditions in the correct order.
## Testing
### Comprehensive Testing
To test the solution comprehensively, include:
- Typical leap years (e.g., 2020, 1968).
- Typical non-leap years (e.g., 2021, 1900).
- Edge cases as identified above.
### Example Test Cases
- `leapYear(2000)` should return `true`.
- `leapYear(1900)` should return `false`.
- `leapYear(2020)` should return `true`.
- `leapYear(2021)` should return `false`.
## Thinking and Problem-Solving Tips
### Tips
- Break down the problem into smaller parts.
- Understand the rules and exceptions thoroughly.
- Use logical operators to combine conditions efficiently.
### Strategies
- Practice similar problems to get comfortable with conditional logic.
- Study the Gregorian calendar rules to understand the context.
## Conclusion
Understanding how to determine leap years is a fundamental problem that tests your ability to apply conditional logic. By breaking down the problem and optimizing the solution, you can handle even the trickiest edge cases efficiently.
## Additional Resources
- [Gregorian Calendar](https://en.wikipedia.org/wiki/Gregorian_calendar)
- [Leap Year Algorithm](https://www.timeanddate.com/date/leapyear.html)
- [Practice Problems on LeetCode](https://leetcode.com/)
By practicing and understanding the underlying principles, you can improve your problem-solving skills and handle similar challenges with ease.
Our interactive tutorials and AI-assisted learning will help you master problem-solving skills and teach you the algorithms to know for coding interviews.
Start Coding for FREE