Kotlin Program to Check Leap Year
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) to test the year and print the result.Examples
How to Think About It
Algorithm
Code
fun main() {
val year = 2024
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
println("$year is a leap year")
} else {
println("$year is not a leap year")
}
}Dry Run
Let's trace the year 1900 through the code
Input year
year = 1900
Check divisibility by 400
1900 % 400 = 300 (not zero), so false
Check divisibility by 4 and not by 100
1900 % 4 = 0 (true) and 1900 % 100 = 0 (true), so condition false because year % 100 == 0
Determine result
Year is not a leap year
| Step | Condition | Result |
|---|---|---|
| Divisible by 400? | 1900 % 400 == 0 | false |
| Divisible by 4? | 1900 % 4 == 0 | true |
| Not divisible by 100? | 1900 % 100 != 0 | false |
| Leap year? | false || (true && false) | false |
Why This Works
Step 1: Divisible by 400 means leap year
If a year divides evenly by 400, it is always a leap year, so we check year % 400 == 0 first.
Step 2: Divisible by 4 but not by 100 means leap year
If the year is divisible by 4 but not by 100, it is a leap year, checked by year % 4 == 0 && year % 100 != 0.
Step 3: Otherwise, not a leap year
If neither condition is true, the year is not a leap year.
Alternative Approaches
fun main() {
val year = 2024
when {
year % 400 == 0 -> println("$year is a leap year")
year % 4 == 0 && year % 100 != 0 -> println("$year is a leap year")
else -> println("$year is not a leap year")
}
}fun isLeapYear(year: Int): Boolean {
return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)
}
fun main() {
val year = 2024
if (isLeapYear(year)) println("$year is a leap year") else println("$year is not a leap year")
}Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of arithmetic and logical operations regardless of input size, so it runs in constant time O(1).
Space Complexity
It uses a fixed amount of memory for variables and no extra data structures, so space complexity is O(1).
Which Approach is Fastest?
All approaches use simple arithmetic checks and run in constant time; using a function improves code reuse but does not affect speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| If-else condition | O(1) | O(1) | Simple and direct checks |
| When expression | O(1) | O(1) | Clear branching syntax |
| Function returning Boolean | O(1) | O(1) | Reusable and clean code |