|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.Calendar; |
| 4 | + |
| 5 | +/** |
| 6 | + * 1154. Day of the Year |
| 7 | + * |
| 8 | + * Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year. |
| 9 | + * |
| 10 | + * Example 1: |
| 11 | + * |
| 12 | + * Input: date = "2019-01-09" |
| 13 | + * Output: 9 |
| 14 | + * Explanation: Given date is the 9th day of the year in 2019. |
| 15 | + * Example 2: |
| 16 | + * |
| 17 | + * Input: date = "2019-02-10" |
| 18 | + * Output: 41 |
| 19 | + * Example 3: |
| 20 | + * |
| 21 | + * Input: date = "2003-03-01" |
| 22 | + * Output: 60 |
| 23 | + * Example 4: |
| 24 | + * |
| 25 | + * Input: date = "2004-03-01" |
| 26 | + * Output: 61 |
| 27 | + * |
| 28 | + * |
| 29 | + * Constraints: |
| 30 | + * |
| 31 | + * date.length == 10 |
| 32 | + * date[4] == date[7] == '-', and all other date[i]'s are digits |
| 33 | + * date represents a calendar date between Jan 1st, 1900 and Dec 31, 2019. |
| 34 | + * */ |
| 35 | +public class _1154 { |
| 36 | + public static class Solution1 { |
| 37 | + Calendar cal = Calendar.getInstance(); |
| 38 | + |
| 39 | + public int dayOfYear(String date) { |
| 40 | + int year = Integer.parseInt(date.substring(0, 4)); |
| 41 | + int month = Integer.parseInt(date.substring(5, 7)); |
| 42 | + int day = Integer.parseInt(date.substring(8, 10)); |
| 43 | + int thirtyDays = 30; |
| 44 | + int thirtyOneDays = 31; |
| 45 | + if (month == 1) { |
| 46 | + return day; |
| 47 | + } else if (month == 2) { |
| 48 | + return day + thirtyOneDays; |
| 49 | + } else { |
| 50 | + int daysInFeb = isLeapYear(year) ? 29 : 28; |
| 51 | + if (month == 3) { |
| 52 | + return thirtyOneDays + daysInFeb + day; |
| 53 | + } else if (month == 4) { |
| 54 | + return 2 * thirtyOneDays + daysInFeb + day; |
| 55 | + } else if (month == 5) { |
| 56 | + return 2 * thirtyOneDays + daysInFeb + day + thirtyDays; |
| 57 | + } else if (month == 6) { |
| 58 | + return 3 * thirtyOneDays + daysInFeb + day + thirtyDays; |
| 59 | + } else if (month == 7) { |
| 60 | + return 3 * thirtyOneDays + daysInFeb + day + 2 * thirtyDays; |
| 61 | + } else if (month == 8) { |
| 62 | + return 4 * thirtyOneDays + daysInFeb + day + 2 * thirtyDays; |
| 63 | + } else if (month == 9) { |
| 64 | + return 5 * thirtyOneDays + daysInFeb + day + 2 * thirtyDays; |
| 65 | + } else if (month == 10) { |
| 66 | + return 5 * thirtyOneDays + daysInFeb + day + 3 * thirtyDays; |
| 67 | + } else if (month == 11) { |
| 68 | + return 6 * thirtyOneDays + daysInFeb + day + 3 * thirtyDays; |
| 69 | + } else { |
| 70 | + return 6 * thirtyOneDays + daysInFeb + day + 4 * thirtyDays; |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + private boolean isLeapYear(int year) { |
| 76 | + cal.set(Calendar.YEAR, year); |
| 77 | + return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365; |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments