1185. Day of the Week

问题:

给出某年某月某日,求该天是周几?

Example 1:
Input: day = 31, month = 8, year = 2019
Output: "Saturday"

Example 2:
Input: day = 18, month = 7, year = 1999
Output: "Sunday"

Example 3:
Input: day = 15, month = 8, year = 1993
Output: "Sunday"
 
Constraints:
The given dates are valid dates between the years 1971 and 2100.

  

解法:

解法一:

Zeller's Formula:

  W=[C/4]-2C+Y+[Y/4]+[13×(M+1)/5]+D-1,

或者是

   W=Y+[Y/4]+[C/4]-2C+[26×(M+1)/10]+D-1

公式都是基于 公历 的置闰规则来考虑。 公式中的符号含义如下:

  • W:星期

  • C:世纪数减一 (年份前两位数)

  • Y:年(年份后两位数)

  • M:月(M的取值范围为3至14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月来计算,比如2003 年1月1日要看作 2002 年的13月1日来计算)

  • D :日

  • []:称作高斯符号,代表取整,即只要整数部份

  • mod:同余‎这里代表括号里的答案除以7后的余数

 

代码参考:

1     vector<string> days= {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
2     string dayOfTheWeek(int d, int m, int y, int c = 0) {
3         if (m < 3) m += 12, y -= 1;
4         c = y / 100, y = y % 100;
5         int w = (c / 4 - 2 * c + y + y / 4 + 13 * (m + 1) / 5 + d - 1) % 7;
6         return days[(w + 7) % 7];
7     }

解法二:

通过已知的 1971-1-1为周五,来进行偏移推算。

⚠️ 注意:闰年判断:(year%100!=0 && year%4==0) || year%400==0

代码参考:

 1 class Solution {
 2 public:
 3     string dayOfTheWeek(int day, int month, int year) {
 4         vector<string> week={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
 5         vector<int> days={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
 6         day-=1;//1971-1-1 Friday
 7         //计算距离从1971-1-1到给定日的前一天(day-=1),一共有多少天。
 8         for(int i=0; i<month-1; i++) day+=days[i];//计算本年度有几个月,month-1个整月+day
 9         if(month>2 && ((year%100!=0 && year%4==0) || year%400==0)) day+=1;
10         for(int i=1971; i<year; i++){//计算有多少年,1971到year-1年+本年度的月数
11             if((i%100!=0 && i%4==0) || i%400==0) day+=366;
12             else day+=365;
13         }
14         return week[(day%7+5)%7];//1971-1-1的Friday=week[5],所以需要偏移5天。
15     }
16 };
原文地址:https://www.cnblogs.com/habibah-chang/p/13254555.html