Skip to content

Commit 2a68a8f

Browse files
solves day of the year
1 parent 756e1ce commit 2a68a8f

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -305,7 +305,7 @@
305305
| 1134 | 🔒 [Armstrong Number](https://leetcode.com/problems/armstrong-number) | | |
306306
| 1137 | [Nth Tribonacci Number](https://leetcode.com/problems/n-th-tribonacci-number) | [![Java](assets/java.png)](src/NthTribonacciNumber.java) | |
307307
| 1150 | [Check if Number is Majority Element in Sorted Array](https://leetcode.com/problems/check-if-a-number-is-majority-element-in-a-sorted-array) | | |
308-
| 1154 | [Day of The Year](https://leetcode.com/problems/day-of-the-year) | | |
308+
| 1154 | [Day of The Year](https://leetcode.com/problems/day-of-the-year) | [![Java](assets/java.png)](src/DayOfTheYear.java) | |
309309
| 1160 | [Find Words That Can Be Formed By Characters](https://leetcode.com/problems/find-words-that-can-be-formed-by-characters) | | |
310310
| 1165 | [Single Row Keyboard](https://leetcode.com/problems/single-row-keyboard) | | |
311311
| 1170 | [Compare Strings By Frequency of the Smallest Character](https://leetcode.com/problems/compare-strings-by-frequency-of-the-smallest-character) | | |

src/DayOfTheYear.java

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
public class DayOfTheYear {
2+
private static final int[] DAYS_UPTO_MONTH_IN_STD_YEAR = {
3+
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
4+
};
5+
6+
private static final int[] DAYS_UPTO_MONTH_IN_LEAP_YEAR = {
7+
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
8+
};
9+
10+
public int dayOfYear(String date) {
11+
String[] dateParts = date.split("-");
12+
final int year = Integer.parseInt(dateParts[0]);
13+
final int month = Integer.parseInt(dateParts[1]);
14+
final int day = Integer.parseInt(dateParts[2]);
15+
if (isLeapYear(year)) {
16+
return DAYS_UPTO_MONTH_IN_LEAP_YEAR[month - 1] + day;
17+
}
18+
return DAYS_UPTO_MONTH_IN_STD_YEAR[month - 1] + day;
19+
}
20+
21+
private boolean isLeapYear(int year) {
22+
if (year % 400 == 0) return true;
23+
if (year % 100 == 0) return false;
24+
return year % 4 == 0;
25+
}
26+
}

0 commit comments

Comments
 (0)