# LeetCode.1185-一周中的星期几(Day of the Week)

## 看题和准备

• 给定的日期是1971年至2100年之间的有效日期。

## 第一种解法

public String dayOfTheWeek(int day, int month, int year) {
String[] week = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, day);
int i = cal.get(Calendar.DAY_OF_WEEK)-1;
if (i<0) {
i = 0;
}
return week[i];
}


## 第二种解法

public String dayOfTheWeek2(int day, int month, int year) {
String[] week = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
int[] dayOfMonth = {31,28,31,30,31,30,31,31,30,31,30,31};
int total = 0;
for (int i=1971; i<year; i++) {
if (i%4 == 0) {
total++;
}
total += 365;
}
if (year%4 == 0) {
dayOfMonth[1] = 29;
}
for (int j=0; j<month-1; j++) {
total += dayOfMonth[j];
}
total += day - 1;
return week[(total + 5)%7];
}


## 第三种解法

w =  (c/4- 2*c + y + y/4 + 26*(m + 1)/10 + d - 1) % 7;

• c:代表世纪，是年份的前两位，比如1971，c就为19。

• y:是年份的后两位，比如1971，y就是71。

• m:代表月，3<= m <= 14，某年的1、2月要看作上一年的13、14月来计算，比如2003年1月1日，要看作2002年的13月1日来计算。

• d:代表日。

• w:计算结果，代表星期几。

public String dayOfTheWeek3(int day, int month, int year) {
String[] week = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday" };
//如果月份小于3月，则月份加12，年份减1
if (month < 3) {
month += 12;
year -= 1;
}
int J = year / 100; // 世纪，年份前两位
int K = year % 100; // 年份，年份后两位
int h = (K + K / 4 + J / 4 - 2 * J +
26 * (month + 1) / 10 + day - 1) % 7;
// h算出来可能为负数，需要补7后再取一次余
return week[(h + 7) % 7];
}


## 第四种解法

Week = (Day + 2*Month + 3*(Month+1)/5 + Year + Year/4 - Year/100 + Year/400) % 7;


public String dayOfTheWeek4(int day, int month, int year) {
String[] week = {"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"};
if (month < 3) {
month += 12;
year -= 1;
}
int w = (day + 2*month + 3*(month+1)/5 +
year + year/4 - year/100 + year/400) % 7;
return week[w];
}


## 小结

posted @ 2019-09-26 08:33  程序员小川  阅读(...)  评论(...编辑  收藏