LeetCode1154-一年中的第几天

题目链接

英文链接:https://leetcode.com/problems/day-of-the-year/

中文链接:https://leetcode-cn.com/problems/ordinal-number-of-date/

题目详述

给你一个按 YYYY-MM-DD 格式表示日期的字符串 date,请你计算并返回该日期是当年的第几天。

通常情况下,我们认为 1 月 1 日是每年的第 1 天,1 月 2 日是每年的第 2 天,依此类推。每个月的天数与现行公元纪年法(格里高利历)一致。

示例 1:

1
2
输入:date = "2019-01-09"
输出:9

示例 2:

1
2
输入:date = "2019-02-10"
输出:41

示例 3:

1
2
输入:date = "2003-03-01"
输出:60

示例 4:

1
2
输入:date = "2004-03-01"
输出:61

提示:

  • date.length == 10
  • date[4] == date[7] == ‘-‘,其他的 date[i] 都是数字。
  • date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日。

题目详解

  • 比较简单,首先分割字符串,得到年月日,然后再计算得到结果。
  • 需要注意如果月份大于二月且是闰年需要额外加一。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class LeetCode_01154 {

int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

public int dayOfYear(String date) {
String[] strs = date.split("-");
int y = Integer.parseInt(strs[0]);
int m = Integer.parseInt(strs[1]);
int d = Integer.parseInt(strs[2]);
int res = 0;
for (int i = 1; i < m; ++i) {
res += days[i];
}
// 大于二月且是闰年额外加一
if (m > 2 && (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))) {
++res;
}
res += d;
return res;
}
}