1185. Day of the Week #
题目 #
-
给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
-
输入为三个整数:
day
、month
和year
,分别表示日、月、年。 -
您返回的结果必须是这几个值中的一个
{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
。
思路 #
模拟 #
代码 #
模拟 #
class Solution {
public boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
public int[] dayOfMonths (int year) {
int[] days = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)) days[1]++;
return days;
}
public String dayOfTheWeek(int day, int month, int year) {
/** 1971/01/01 is Friday. */
/** 1. 推断出year/month/day这一天距离1971/01/01过去了多少days */
int days = 0;
if (year == 1971) {
/** 计算1971/month/day这一天距离1971/01/01过去了多少天 */
for(int i = 0; i < month - 1; i++) days += dayOfMonths(year)[i];
days += day - 1;
}
else {
for (int i = 1971; i < year; i++) days += isLeapYear(i) ? 366 : 365;
for (int i = 0; i < month - 1; i++) days += dayOfMonths(year)[i];
days += day - 1;
}
/** 2. 用days对7取模*/
switch (days % 7) {
case 0 : return "Friday";
case 1 : return "Saturday";
case 2 : return "Sunday";
case 3 : return "Monday";
case 4 : return "Tuesday";
case 5 : return "Wednesday";
case 6 : return "Thursday";
}
/** 3. 返回答案 */
return "";
}
}