LeetCode 1154. 【Java】1154. Day of the Year
原题链接
简单
作者:
tt2767
,
2020-02-27 23:00:18
,
所有人可见
,
阅读 782
/*
1. 今年有多少天 = 这个月之前有多少天 + 今天是当月的第几天 + 闰年补充天
2. 这个月之前有多少天 -> 前缀和 制备好
*/
class Solution {
static int MONTH_NUMBER = 12;
static int[] dayOfMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
static int[] prefixSum = initPrefixSum();
public int dayOfYear(String date) {
String[] dateTime = date.split("-");
int year = Integer.parseInt(dateTime[0]);
int month = Integer.parseInt(dateTime[1]);
int day = Integer.parseInt(dateTime[2]);
int extra = isLeapYear(year) && month > 2 ? 1 : 0 ;
return prefixSum[month-1] + day + extra;
}
private static int[] initPrefixSum(){
int[] prefixSum = new int[MONTH_NUMBER + 1];
for (int i = 1; i <= MONTH_NUMBER ; i++){
prefixSum[i] += prefixSum[i-1] + dayOfMonth[i];
}
return prefixSum;
}
private boolean isLeapYear(int y){
return (y % 4 == 0) && !(y % 100 == 0 && y % 400 != 0);
}
}