// Package leap is a small library for determing if the passed in year is a leap year.
package leap
// IsLeapYear returns if the passed in year is a leap year.
func IsLeapYear(year int) bool {
return year%4 == 0 && (year%100 != 0 || year%400 == 0)
}
The first boolean expression uses the modulus operator to check if the year is evenly divided by 4.
- If the year is not evenly divisible by
4, then the chain will "short circuit" due to the next operator being a logical AND (&&), and will returnfalse. - If the year is evenly divisible by
4, then the year is checked to not be evenly divisible by100. - If the year is not evenly divisible by
100, then the expression istrueand the chain will "short-circuit" to returntrue, since the next operator is a logical OR (||). - If the year is evenly divisible by
100, then the expression isfalse, and the returned value from the chain will be if the year is evenly divisible by400.
This approach exhausts after a maximum of three checks.
| year | year % 4 == 0 | year % 100 != 0 | year % 400 == 0 | is leap year |
|---|---|---|---|---|
| 2020 | true | true | not evaluated | true |
| 2019 | false | not evaluated | not evaluated | false |
| 2000 | true | false | true | true |
| 1900 | true | false | false | false |
7th Aug 2024
·
Found it useful?