1154.一年中的第几天
题目描述
思路
模拟
根据题意模拟即可。需要考虑闰年的因素。
Python实现
class Solution:
def dayOfYear(self, date: str) -> int:
days = [0] + list(accumulate([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]))
y, m, d = int(date[:4]), int(date[5:7]), int(date[-2:])
if m > 2 and (y % 400 == 0 or (y % 4 == 0 and y % 100 != 0)):
return days[m-1] + d + 1
return days[m-1] + d
Java实现
class Solution {
private static final int[] days = new int[]{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static{
for(int i=1;i<days.length;i++)
days[i] += days[i-1];
}
public int dayOfYear(String date) {
String[] sd = date.split("-");
int y = Integer.parseInt(sd[0]), m = Integer.parseInt(sd[1]), d = Integer.parseInt(sd[2]);
return days[m - 1] + d + ((m > 2 && (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))) ? 1 : 0);
}
}