diff --git a/README.md b/README.md index 0704269..050ab37 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,7 @@ Algorithm、Review、Tip、Share |703|[Kth Largest Element in a Stream](https://leetcode.com/problems/kth-largest-element-in-a-stream/)|[Java](./week06/algo/lc703/KthLargest.java)|Easy| |1103|[Distribute Candies to People](https://leetcode.com/problems/distribute-candies-to-people/)|[Java](./week14/algo/lc1103/Solution.java)|Easy| |1108|[Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/)|[Java](./week16/algo/lc1108/Solution.java)|Easy| +|1154|[Day of the Year](https://leetcode.com/problems/day-of-the-year/)|[Java](./week24/algo/lc1154/Solution.java)|Easy| ## Review diff --git a/week24/algo/lc1154/Solution.java b/week24/algo/lc1154/Solution.java new file mode 100644 index 0000000..4c1c0b9 --- /dev/null +++ b/week24/algo/lc1154/Solution.java @@ -0,0 +1,35 @@ +package com.milley.dayoftheyear; + +public class Solution { + public static int dayOfYear(String date) { + char[] dateArray = date.toCharArray(); + int totalDays = 0; + int year, month, day; + + int[] DAYS_OF_MONTH = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + year = 1000 * (dateArray[0] - '0') + 100 * (dateArray[1] - '0') + + 10 * (dateArray[2] - '0') + (dateArray[3] - '0'); + month = 10 * (dateArray[5] - '0') + (dateArray[6] - '0'); + day = 10 * (dateArray[8] - '0') + (dateArray[9] - '0'); + + boolean isLeafYear = (year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0); + if (month > 2 && isLeafYear) { + totalDays += 1; + } + while (month > 1) { + totalDays += DAYS_OF_MONTH[month - 2]; + month--; + } + totalDays += day; + + return totalDays; + } + + public static void main(String[] args) { + System.out.println(dayOfYear("2019-01-09")); + System.out.println(dayOfYear("2019-02-10")); + System.out.println(dayOfYear("2003-03-01")); + System.out.println(dayOfYear("2004-03-01")); + } +}