Java刷题随笔---1154. 一年中的第几天

1154. 一年中的第几天 - 力扣(LeetCode) (leetcode-cn.com)

难度:简单
题目描述:给你一个字符串 date ,按 YYYY-MM-DD 格式表示一个 现行公元纪年法 日期。请你计算并返回该日期是当年的第几天。
通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。每个月的天数与现行公元纪年法(格里高利历)一致。

分析

此题较为基础, 
首先使用date.substring()方法计算出date的年月日 
之后转换成数字形式 
年分为两种情况 
一种闰年,二月多一天 
一种非闰年 
设定非闰年的每月天数为[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] 
做一个循环,截止为month - 1,因为最后一个月的天数由day决定

解题

class Solution {
    public int dayOfYear(String date) {
            int result = 0;
            int year = Integer.valueOf(date.substring(0,4));
            int month = Integer.valueOf(date.substring(5,7));
            int day = Integer.valueOf(date.substring(8,10));
            int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
            if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
                days[1]++;
            }
            for (int i = 0; i < month - 1; i++) {
                result += days[i];
            }
            return result + day;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容