Created
January 27, 2020 07:28
-
-
Save Howiezhang226/d1644fd3e11fc4f76bc07447380b06b6 to your computer and use it in GitHub Desktop.
Day of the Year
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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