题目
类型:数学
解题思路
由于每年月份的天数都相对固定(仅有闰年 22 月份不同),因此可以使用 static 进行打表预处理。
使用 nums 构建一个平年的月份数组,再通过「前缀和」得到平年的每个月的天数总和。
最后将 date
按照 -
分割为年月日,分别进行计数。
注意,当年份为闰年且当前月份超过了 2 月份,要追加一天。
代码
class Solution {
static int[] nums = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static int[] f = new int[13];
static {
for (int i = 1; i <= 12; i++) f[i] = f[i - 1] + nums[i - 1];
}
public int dayOfYear(String date) {
String[] ss = date.split("-");
int y = Integer.parseInt(ss[0]), m = Integer.parseInt(ss[1]), d = Integer.parseInt(ss[2]);
boolean isLeap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
int ans = m > 2 && isLeap ? f[m - 1] + 1 : f[m - 1];
return ans + d;
}
}