There are various idiomatic approaches to solve Leap. You can use a chain of boolean expressions to test the conditions. Or you can use a ternary operator.
The key to solving Leap is to know if the year is evenly divisible by 4
, 100
and 400
.
For determining that, you will use the remainder operator.
boolean isLeapYear(int year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
For more information, check the Boolean chain approach.
boolean isLeapYear(int year) {
return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0;
}
For more information, check the Ternary operator approach.
Besides the aforementioned, idiomatic approaches, you could also approach the exercise as follows:
Add a day to February 28th for the year and see if the new day is the 29th. For more information, see the plusDays()
approach.
Use the built-in method for the Year. For more information, see the isLeap()
approach.
- The chain of boolean expressions is most efficient, as it proceeds from the most likely to least likely conditions. It has a maximum of three checks.
- The ternary operator has a maximum of only two checks, but it starts from a less likely condition.
- Using
plusDays()
or using the built-inisLeap()
method may be considered "cheats" for the exercise, butisLeap()
would be the idiomatic way to check if a year is a leap year in Java.