给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
输入为三个整数:day、month 和 year,分别表示日、月、年。
您返回的结果必须是这几个值中的一个 {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}。
示例 1:
输入:day = 31, month = 8, year = 2019
输出:”Saturday”
示例 2:
输入:day = 18, month = 7, year = 1999
输出:”Sunday”
示例 3:
输入:day = 15, month = 8, year = 1993
输出:”Sunday”
提示:
给出的日期一定是在 1971 到 2100 年之间的有效日期。
class Solution {
//因为是从1971年1月1日起算的,1是Friday
static String[] weeks = new String[]{"Thursday","Friday","Saturday","Sunday","Monday","Tuesday","Wednesday"};
static Map<Integer,Integer> map = new HashMap<>();
//预处理一下map
static {
int sum = 0;
map.put(1970,0);
for (int i = 1971; i <= 2100; ++i) {
sum += 365;
//判断是否是闰年
if (i % 400 == 0 || (i % 4 == 0 && i % 100 != 0))
sum ++;
map.put(i,sum);
}
}
public String dayOfTheWeek(int day, int month, int year) {
//先加上1971到year-1年有多少天
int days = map.get(year-1);
int[] months = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
//month-1个月之前有多少天
for (int i = 0; i <= month-2; i++) days += months[i];
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
if (month > 2) days ++;
//加上天数
days += day;
//1971年1月1日是星期五
int week = days % 7;
return weeks[week];
}
}