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. The day number is the number of days from January 1st to the given date.
Example 1:
Input: date = "2019-01-09"
Output: 9
Example 2:
Input: date = "2019-02-10"
Output: 41
public class Solution {
public int dayOfYear(String date) {
String[] dateParts = date.split("-");
int year = Integer.parseInt(dateParts[0]);
int month = Integer.parseInt(dateParts[1]);
int day = Integer.parseInt(dateParts[2]);
int[] daysInMonthsNonLeap = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int[] daysInMonthsLeap = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
boolean isLeapYear = isLeapYear(year);
int[] daysInMonths = isLeapYear ? daysInMonthsLeap : daysInMonthsNonLeap;
int dayOfYear = 0;
for (int i = 0; i < month - 1; i++) {
dayOfYear += daysInMonths[i];
}
dayOfYear += day;
return dayOfYear;
}
private boolean isLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
return year % 400 == 0;
}
return true;
}
return false;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.dayOfYear("2019-01-09")); // Outputs 9
System.out.println(sol.dayOfYear("2019-02-10")); // Outputs 41
System.out.println(sol.dayOfYear("2000-03-01")); // Outputs 61
}
}
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?