问题描述
给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
输入为三个整数: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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
执行结果
代码描述
思路之一:找现有函数。——来自解题报告
#include<time.h>
class Solution {
public: string dayOfTheWeek(int day, int month, int year) {//1970/1/1 thursdaychar *weeknames[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};tm now = {.tm_mday = day,.tm_mon = month - 1,.tm_year = year - 1900};mktime(&now);return weeknames[now.tm_wday];}
};
思路之二:知道起始那天是周几,然后对7取余计算当前是周几。——来自解题报告
class Solution {
public:string dayOfTheWeek(int day, int month, int year) {//1970/1/1 thursdaychar *weeknames[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};int mday[]={31,28,31,30,31,30,31,31,30,31,30,31};int wday = 4;int i = 0;for (i=1970; i<year; i++){if((i%4==0 && i%100!=0) || i%400==0){wday += (366%7);}else{wday += (365%7);}}if((i%4==0 && i%100!=0) || i%400==0){mday[1]++;}wday %= 7;for(i=1; i<month; i++){wday += mday[i-1] % 7;}wday += day-1;wday %= 7;return string(weeknames[wday]);}
};