This is rather easier if you can have access to a calendar to check if a certain year is a leap year, otherwise, you need to memorize this criteria to check if a year is a leap year:
year % 4 == 0 && year % 100 > 0 || year % 400 == 0
class Solution {
fun numberOfDays(Y: Int, M: Int): Int {
return when {
M == 1 || M == 3 || M == 5 ||
M == 7 || M == 8 || M == 10 || M == 12 -> 31
else -> {
if(M == 2) {
if(isLeapYear(Y)) 29 else 28
}else 30
}
}
}
private fun isLeapYear(year: Int): Boolean = year % 4 == 0 && year % 100 > 0 || year % 400 == 0
}
Runtime: 112 ms, faster than 100.00% of Kotlin online submissions for Number of Days in a Month.
Memory Usage: 30.7 MB, less than 100.00% of Kotlin online submissions for Number of Days in a Month.