Sum complete preceding month lengths, add the current day, and include February's leap day when the year is leap and the date is after February.
Complexity
O(1) time and O(1) space.
Convert an ISO calendar date to its one-based ordinal day within the year.
Sum complete preceding month lengths, add the current day, and include February's leap day when the year is leap and the date is after February.
O(1) time and O(1) space.
package main
import "strconv"
func dayOfYear(date string) int {
year, _ := strconv.Atoi(date[:4])
month, _ := strconv.Atoi(date[5:7])
day, _ := strconv.Atoi(date[8:])
days := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
ordinal := day
for index := 0; index < month-1; index++ {
ordinal += days[index]
}
if month > 2 && (year%400 == 0 || year%4 == 0 && year%100 != 0) {
ordinal++
}
return ordinal
}
class Solution:
def dayOfYear(self, date: str) -> int:
year, month, day = map(int, date.split("-")); days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leap = year % 400 == 0 or year % 4 == 0 and year % 100 != 0
return sum(days[:month - 1]) + day + int(leap and month > 2)
function dayOfYear(date: string): number {
const [year, month, day] = date.split("-").map(Number); const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let ordinal = day; for (let index = 0; index < month - 1; index += 1) ordinal += days[index];
const leap = year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0); return ordinal + Number(leap && month > 2);
}