LeetCode - Algorithms - 1154. Day of the Year

Problem

1154. Day of the Year

Java

my solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
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,10));
int[] dayOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
boolean leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
if (leapYear)
dayOfMonth[1] = 29;
int dy = day;
for (int i = 1; i < month; i++) {
dy += dayOfMonth[i - 1];
}
return dy;
}
}

Submission Detail

  • 246 / 246 test cases passed.
  • Runtime: 1 ms, faster than 98.63% of Java online submissions for Day of the Year.
  • Memory Usage: 37.1 MB, less than 7.99% of Java online submissions for Day of the Year.

java8 LocalDate

1
2
3
4
5
6
7
8
9
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

class Solution {
public int dayOfYear(String date) {
LocalDate d = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
return d.getDayOfYear();
}
}

Submission Detail

  • 246 / 246 test cases passed.
  • Runtime: 16 ms, faster than 6.07% of Java online submissions for Day of the Year.
  • Memory Usage: 38.3 MB, less than 7.64% of Java online submissions for Day of the Year.