Leetcode 1154. Day of the Year
Given a string date
representing a Gregorian calendar date formatted as YYYY-MM-DD
, return the day number of the year.
For instance:
date = "2019-01-09"
Output: 9
date = "2019-02-10"
Output: 41
date = "2003-03-01"
Output: 60
date = "2004-03-01"
61
YYYY
, MM
, and DD
.#include <iostream>
#include <string>
#include <vector>
class Solution {
public:
int dayOfYear(std::string date) {
int year = std::stoi(date.substr(0, 4));
int month = std::stoi(date.substr(5, 2));
int day = std::stoi(date.substr(8, 2));
std::vector<int> days_in_month_non_leap = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
std::vector<int> days_in_month_leap = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// Function to check if a year is a leap year
auto is_leap_year = [](int year) -> bool {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
};
std::vector<int> days_in_month = is_leap_year(year) ? days_in_month_leap : days_in_month_non_leap;
// Calculate the day of year
int day_of_year = 0;
for (int i = 0; i < month - 1; ++i) {
day_of_year += days_in_month[i];
}
day_of_year += day;
return day_of_year;
}
};
int main() {
Solution solution;
std::string date1 = "2019-01-09";
std::cout << solution.dayOfYear(date1) << std::endl; // Output: 9
std::string date2 = "2019-02-10";
std::cout << solution.dayOfYear(date2) << std::endl; // Output: 41
std::string date3 = "2003-03-01";
std::cout << solution.dayOfYear(date3) << std::endl; // Output: 60
std::string date4 = "2004-03-01";
std::cout << solution.dayOfYear(date4) << std::endl; // Output: 61
return 0;
}
This ensures the solution is efficient and runs in constant time regardless of the date provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?