# 1154. Day of the Year¶

• Time:
• Space:
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution { public: int dayOfYear(string date) { int year = stoi(date.substr(0, 4)); int month = stoi(date.substr(5, 2)); int day = stoi(date.substr(8)); vector days = { 31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; return accumulate(days.begin(), days.begin() + month - 1, 0) + day; } private: bool isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Solution { public int dayOfYear(String date) { int ans = 0; int year = Integer.valueOf(date.substring(0, 4)); int month = Integer.valueOf(date.substring(5, 7)); int day = Integer.valueOf(date.substring(8)); int[] days = new int[] {31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; for (int i = 0; i < month - 1; ++i) ans += days[i]; return ans + day; } private boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 class Solution: def dayOfYear(self, date: str) -> int: def isLeapYear(year: int) -> bool: return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 year = int(date[:4]) month = int(date[5:7]) day = int(date[8:]) days = [31, 29 if isLeapYear( year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] return sum(days[:month - 1]) + day