1154. 一年中的第几天 --力扣 --JAVA

题目

给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。返回该日期是当年的第几天。

解题思路

  1. 将每个月包含的日期数枚举出来(12月可枚举也可不枚举);
  2. 通过分割字符串获取当前日期的年、月、日;
  3. 计算当前年份是否为闰年,若是则修改二月份的日期为29,默认为28;
  4. 当月天数加上之前每个月的天数。

代码展示

class Solution {
    private int[] days = new int[]{31,28,31,30,31,30,31,31,30,31,30};
    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));
        int ans = day;
        if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)){
            days[1] = 29;
        }
        for(int i = 1; i < month; i++){
            ans += days[i - 1];
        }
        return ans;
    }
}

你可能感兴趣的:(力扣练习,算法,数据结构)