Skip to content

Instantly share code, notes, and snippets.

@Howiezhang226
Created January 27, 2020 07:28
Show Gist options
  • Save Howiezhang226/d1644fd3e11fc4f76bc07447380b06b6 to your computer and use it in GitHub Desktop.
Save Howiezhang226/d1644fd3e11fc4f76bc07447380b06b6 to your computer and use it in GitHub Desktop.
Day of the Year
class Solution {
public int dayOfYear(String date) {
int[] daysOfTheMonth = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int days = 0;
String[] split = date.split("-");
int year = Integer.valueOf(split[0]);
int month = Integer.valueOf(split[1]);
int day = Integer.valueOf(split[2]);
for (int i = 0 ; i < month - 1; i++) {
days += daysOfTheMonth[i];
}
days += day;
if (isLeapYear(year) && month > 2) {
days++;
}
return days;
}
private boolean isLeapYear(int year) {
return year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment