1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { private static final int[] DAYS_PER_MONTH = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public int dayOfYear(String date) { int year = Integer.parseInt(date.substring(0, 4)); int month = Integer.parseInt(date.substring(5, 7)); int day = Integer.parseInt(date.substring(8));
boolean isLeapYear = isLeapYear(year); int result = 0; for (int i = 1; i < month; i++) { result += DAYS_PER_MONTH[i]; if (i == 2 && isLeapYear) { result++; } } result += day;
return result; }
private boolean isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; } }
|