【leetcode题解】日期计算:leetcode1185. Day of the Week

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the daymonth and year respectively.

Return the answer as one of the following values {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}.

 

Example 1:

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

Example 2:

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

Example 3:

Input: day = 15, month = 8, year = 1993Output: "Sunday"

 

Constraints:

  • The given dates are valid dates between the years 1971 and 2100.


Solution:


/**
 * 思路:网上查到一个快捷公式。否则处理闰年的情况,代码会写很长。。这里偷鸡一下 :(
 * 基姆拉尔森计算公式
 * W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400+1) mod 7
 * 注意把 一月和 二月换成上个月的 13月和14月来计算
 */
class Solution {
public:
    string dayOfTheWeek(int day, int month, int year) {
    	if(month == 1 || month == 2) {
    		month += 12;
    		year--;
    	}

        int W = (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400 + 1) % 7;

        switch(W) {
        	case 0:
        		return "Sunday";
        	case 1:
        		return "Monday";
        	case 2:
        		return "Tuesday";
        	case 3:
        		return "Wednesday";
        	case 4:
        		return "Thursday";
        	case 5:
        		return "Friday";
        	case 6:
        		return "Saturday";
        }

        string s = "Monday";        // 这里无意义,只是因为 leetcode 的编译器要求必须有一个返回值,实际上不可能走到这里,但还是要加上一句。
        return s;
    }
};


发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

Powered By Z-BlogPHP 1.5.2 Zero

Copyright liuyang1.com. 转载文章,请注明出处。谢谢!