题目
给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
输入为三个整数: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 年之间的有效日期。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/day-of-the-week
解题思路
法一:暴力
判断是否是闰年,再根据输入的年月日计算过去了多少天。
法二:模拟
把 1971-01-01 为基底 , 开始不断接近 题目给出的日期即可。
法三:蔡勒公式
这个没学过,记一下 注意:由于最 D 可能为负数,需要处理一下。方法很多:这里由 D 计算式发现减的内容最大为 199 所以可以加上一个大于 199 且是 7 的倍数的数。
法四:用现成的包
LocalDate类是Java 8中日期时间功能里表示一个本地日期的类,它的日期是无时区属性的。直接调用即可。
代码
法一
class Solution {
public String dayOfTheWeek(int day, int month, int year) {
String[] week = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
int sum = 0;
for(int i = 1971; i < year; i++){
if(is_leap(i)){
sum += 366;
}
else{
sum += 365;
}
}
for(int i = 0; i < month-1; i++){
sum += monthDays[i];
}
if(month > 2 && is_leap(year)){
sum += 1 + day;
}
else{
sum += day;
}
int temp = sum%7;
return week[(temp+3)%7];
}
public boolean is_leap(int year){
if((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)){
return true;
}
return false;
}
}
法二:
class Solution {
public String dayOfTheWeek(int day, int month, int year) {
String[] week = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
int[] monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
int days = 365 * (year - 1971) + (year - 1969) / 4;
for (int i = 0; i < month - 1; ++i) {
days += monthDays[i];
}
if ((year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) && month >= 3) {
days += 1;
}
days += day;
return week[(days + 3) % 7];
}
}
法三:
class Solution {
public String dayOfTheWeek(int day, int month, int year) {
String week[] = { "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"} ;
int m ,y;
if (month < 3) {
m = month + 12;
y = year - 1;
} else {
m = month;
y = year;
}
int index = 0 ;
index = (day + 13 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7 ;
return week[index] ;
}
}
法四
import java.time.LocalDate;
class Solution {
public String dayOfTheWeek(int day, int month, int year) {
LocalDate localDate = LocalDate.of(year,month,day);
String [] s = {null, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday","Sunday"};
return s[localDate.getDayOfWeek().getValue()];
}
}
|