g1101_1200.s1154_day_of_the_year.Solution.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-kotlin Show documentation
Show all versions of leetcode-in-kotlin Show documentation
Kotlin-based LeetCode algorithm problem solutions, regularly updated
package g1101_1200.s1154_day_of_the_year
// #Easy #String #Math #2023_05_25_Time_317_ms_(70.00%)_Space_59.3_MB_(20.00%)
class Solution {
fun dayOfYear(date: String): Int {
val monthDays = intArrayOf(0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
val dateArr = date.split("-".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val year = dateArr[0].toInt()
val month = dateArr[1].toInt()
val day = dateArr[2].toInt()
var dayCount = 0
val leapYear = year % 4 == 0 && year % 100 != 0 || year % 400 == 0
for (i in 1 until month) {
dayCount += monthDays[i]
}
dayCount += day
if (leapYear && month > 2) {
dayCount++
}
return dayCount
}
}