题目地址:https://leetcode-cn.com/problems/day-of-the-year/
给你一个按 YYYY-MM-DD 格式表示日期的字符串date,请你计算并返回该日期是当年的第几天。 通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。 每个月的天数与现行公元纪年法(格里高利历)一致。
示例 1:
输入:date = "2019-01-09"
输出:9
示例 2:
输入:date = "2019-02-10"
输出:41
https://leetcode-cn.com/problems/day-of-the-year/
示例 3:
输入:date = "2003-03-01"
输出:60
示例 4:
输入:date = "2004-03-01"
输出:61
提示:
date.length == 10 date[4] == date[7] == '-',其他的date[i]都是数字。
date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日。
https://leetcode-cn.com/problems/day-of-the-year/
这道题的题意就是,给你一个年月日,返回这一天是当年的第几天。
首先要明确的是,当前月份之前的所有月份日都要加上,然后在加上给的日即可,这里引出一个问题,就是前面所有月份中,二月份又可能碰上闰年就会+1,所以还要对是否闰年进行判断
一、爆破法:
我们提供的数组,是当前月份-1作为下标去数组中获取的这个月之前的天数。
闰年的计算方式是,必须能整除4,且整除100的不算,但整除400的算。
执行结果如下:
10957 / 10957 个通过测试用例
状态:通过
执行用时: 11 ms
内存消耗: 38.9 MB
public static final int[] monthArr = {0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
public static int dayOfYearMe(String date) {
int ans = 0;
int month = Integer.parseInt(date.substring(5, 7));
ans = monthArr[month-1];
if (2 < month) {
ans += isLeapYear(date) ? 1 : 0;
}
return ans += Integer.parseInt(date.substring(8));
}
public static boolean isLeapYear(String date) {
int year = Integer.parseInt(date.substring(0,4));
return (year & 3) == 0 && (year % 100 != 0 || year % 400 == 0);
}
二、爆破法二
方法2在方法一基础上,修改了一些细节,差别不大
执行结果如下:
10957 / 10957 个通过测试用例
状态:通过
执行用时: 10 ms
内存消耗: 39 MB
public static int dayOfYearMe2(String date) {
int ans = 0;
int year = Integer.parseInt(date.substring(0,4));
int month = Integer.parseInt(date.substring(5,7));
int day = Integer.parseInt(date.substring(8));
int[] monthArr = {0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
ans = monthArr[month-1];
ans += day;
if (month > 2 && ( year % 400 == 0 || ((year & 3) == 0 && year % 100 != 0))) {
ans += 1;
}
return ans;
}
我的答案得分很低,我尝试运行评论区中双百大佬的答案也和我差不多,而且内存和时间也没有他们截图的那么小。所以这道题找了半天都没有接近双百的,就这样搁置了(总感觉是力扣出了问题hhhhh)