LeetCode 1154: Day of the Year Solution
Master LeetCode problem 1154 (Day of the Year), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we need to parse the input date string to extract the year, month, and day. Then, we calculate the day number of the year based on the given date.
- Parse the input date string to extract the year, month, and day.
- Calculate the day number of the year based on the given date by summing up the days in previous months and adding the current day.
Time Complexity: O(1)
Space Complexity: O(1)
:
Solution Code
class Solution {
public int dayOfYear(String date) {
int[] daysInMonth = {0,31,28,31,30,31,30,31,31,30,31,30,31};
String[] parts = date.split("-");
int year = Integer.parseInt(parts[0]);
int month = Integer.parseInt(parts[1]);
int day = Integer.parseInt(parts[2]);
int days = day;
for (int i = 1; i < month; i++) {
days += daysInMonth[i];
}
if (month > 2 && isLeapYear(year)) {
days++;
}
return days;
}
private boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1154 (Day of the Year)?
This page provides optimized solutions for LeetCode problem 1154 (Day of the Year) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1154 (Day of the Year)?
The time complexity for LeetCode 1154 (Day of the Year) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1154 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1154 in Java, C++, or Python.