1154. 一年中的第几天

题目:https://leetcode-cn.com/problems/day-of-the-year/

代码:

class Solution {

    public int dayOfYear(String date) {
        //解析出年月日
        String[] dateStr = date.split("-");
        int y = Integer.valueOf(dateStr[0]);
        int m = Integer.valueOf(dateStr[1]);
        int d = Integer.valueOf(dateStr[2]);
        //定义1-12月,每个月的天数
        int[] month = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

        int day = 0;
        //计算m-1个月的总天数
        for (int i = 0; i < m - 1; i++) {
            day += month[i];
        }
        //加上第m月的天数
        day = day + d;
        //如果是闰年,且月份大于2月,则需要加1天(闰年2月多一天)
        if (m > 2) {
            if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
                day = day + 1;
            }
        }
        return day;
    }

}

将年月日解析出来,然后设定一个数组,提前定义好1-12月每个月的天数,考虑一下闰年的问题,即可获得答案。


觉得内容还不错?打赏个钢镚鼓励鼓励!!👍