Day of the Year

easy math date leap year

Problem

Given a string date in the format YYYY-MM-DD, return the day number of the year that this date represents (a value between 1 and 366).

Inputdate = "2019-02-10"
Output41
January has 31 days, then 10 more days into February: 31 + 10 = 41.

def day_of_year(date):
    year, month, day = map(int, date.split("-"))
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
        days[1] = 29
    total = day
    for m in range(month - 1):
        total += days[m]
    return total
function dayOfYear(date) {
  const [year, month, day] = date.split("-").map(Number);
  const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) {
    days[1] = 29;
  }
  let total = day;
  for (let m = 0; m < month - 1; m++) total += days[m];
  return total;
}
class Solution {
    public int dayOfYear(String date) {
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(5, 7));
        int day = Integer.parseInt(date.substring(8, 10));
        int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
            days[1] = 29;
        }
        int total = day;
        for (int m = 0; m < month - 1; m++) total += days[m];
        return total;
    }
}
int dayOfYear(string date) {
    int year = stoi(date.substr(0, 4));
    int month = stoi(date.substr(5, 2));
    int day = stoi(date.substr(8, 2));
    int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
        days[1] = 29;
    }
    int total = day;
    for (int m = 0; m < month - 1; m++) total += days[m];
    return total;
}
Time: O(1) Space: O(1)