和日期相关的代码和bug——一道力扣题中的小发现

目录

Day of the Week

题目大意

常规方法

Python代码

Golang代码

 C++代码

基姆拉尔森公式

Python代码

Golang代码

C++代码

使用库函数

Python代码

Golang代码

C++代码


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 day , month 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 = 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"

题目大意

给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。
输入为三个整数: day、 month 和 year,分别表示日、月、年。
您返回的结果必须是这几个值中的一个 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"}。
提示:
给出的日期一定是在 1971 到 2100 年之间的有效日期。
解题思路:
给出一个日期,要求算出这一天是星期几。

常规方法

从1971.1.1起,先累计整年year、整月month-1的天数,再加上最后一个月month的天数day,然后总天数减1后与7求余。最后得到的余数在星期字串数组中位置索引,显然前提要知道1971.1.1这个基准日期是星期几,再作一个索引位移就是答案。

另外常规方法还需要判断year是否闰年,规则:y%4==0 and y%100!=0 or y%400==0,据说是1582

Python代码

python代码非常简单,不需另外导入库只用内置函数就能搞定。

class Solution(object):
    def DayOfWeek(self, year, month, day):
        days = 0
        isLeapYear = lambda y:y%4==0 and y%100!=0 or y%400==0
        monthday = [31,28,31,30,31,30,31,31,30,31,30,31]
        week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
        monthday[1] = 29 if isLeapYear(year) else 28
        for i in range(1971,year):
            days += 366 if isLeapYear(i) else 365
        days += sum(monthday[:month-1], day-1)
        return week[(days+5)%7]
if __name__ == "__main__":
    s = Solution()
    print(s.DayOfWeek(2019,8,31))
    print(s.DayOfWeek(1999,7,18))
    print(s.DayOfWeek(1993,8,15))
    print(s.DayOfWeek(1971,6,12))
    print(s.DayOfWeek(2023,2,22))
    print(s.DayOfWeek(2040,6,13))

输出:

Saturday
Sunday
Sunday
Saturday
Wednesday
Wednesday

Golang代码

基本原理相同,另外自定义一个数组求和公式即可。

package main
import "fmt"
func DayOfWeek(year int, month int, day int) string {
	days := 0
	isLeapYear := func(y int) bool {
		return y%4 == 0 && y%100 != 0 || y%400 == 0
	}
	Sum := func(nums []int, initNum int) int {
		var sumNum int = 0
		for _, num := range nums {
			sumNum += num
		}
		return sumNum + initNum
	}
	monthday := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
	week := []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
	if isLeapYear(year) {
		monthday[1] = 29
	} else {
		monthday[1] = 28
	}
	for i := 1971; i < year; i++ {
		if isLeapYear(i) {
			days += 366
		} else {
			days += 365
		}
	}
	days += Sum(monthday[:month-1], day-1)
	return week[(days+5)%7]
}
func main() {
	fmt.Println(DayOfWeek(2019, 8, 31))
	fmt.Println(DayOfWeek(1999, 7, 18))
	fmt.Println(DayOfWeek(1993, 8, 15))
	fmt.Println(DayOfWeek(1971, 6, 12))
	fmt.Println(DayOfWeek(2023, 2, 22))
	fmt.Println(DayOfWeek(2040, 6, 13))
}

输出:

Saturday

Sunday

Sunday

Saturday

Wednesday

Wednesday

成功: 进程退出代码 0.

 C++代码

引入C++11的容器vector,可以省掉最后一个非整年的各月份日数循环累加,只要用<numeric>库中的函数accumulate,方便累加非整年的各月份日数,并且把day作为基准数一并累加掉。

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
class Solution
{
public:
    string DayOfWeek(int year, int month, int day)
    {
		int days = 0;
		auto isLeapYear = [](int y) { return y%4==0 && y%100!=0 || y%400==0; };
        vector<int> monthday = {31,28,31,30,31,30,31,31,30,31,30,31};
        vector<string> week = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
		monthday[1] = isLeapYear(year) ? 29 : 28;
		for (int i=1971;i<year;i++)
			days += isLeapYear(i) ? 366 : 365;
		days += accumulate(monthday.begin(), monthday.begin()+month-1, day-1);
        return week[(days+5)%7];
    }
};
int main()
{
	Solution s;
	cout << s.DayOfWeek(2019,8,31) << endl;
	cout << s.DayOfWeek(1999,7,18) << endl;
	cout << s.DayOfWeek(1993,8,15) << endl;
	cout << s.DayOfWeek(1971,6,12) << endl;
	cout << s.DayOfWeek(2023,2,22) << endl;
	cout << s.DayOfWeek(2040,6,13) << endl;
	return 0;
}

Dev C++ 6.3 编译通过:

Saturday
Sunday
Sunday
Saturday
Wednesday
Wednesday

--------------------------------
Process exited after 0.02175 seconds with return value 0
请按任意键继续. . .

基姆拉尔森公式

万能的日期计算公式,不用知道基准日是哪一天,也不需要判断year是否为闰年。

公式:weekday = (day+2month+3(month+1)/5+year+year/4-year/100+year/400+1)%7

注意:1月和2月需看做上一年的13月与14月,即 month<3时, year-=1; month+=12

Python代码

class Solution(object):
    def DayOfWeek(self, year, month, day):
        week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
        if month<3: year, month = year-1, month+12
        weekday = (day+2*month+3*(month+1)//5+year+year//4-year//100+year//400+1)%7
        return dict(zip(range(7),week)).get(weekday)
if __name__ == "__main__":
    s = Solution()
    print(s.DayOfWeek(2019,8,31))
    print(s.DayOfWeek(1999,7,18))
    print(s.DayOfWeek(1993,8,15))
    print(s.DayOfWeek(1971,6,12))
    print(s.DayOfWeek(2023,2,22))
    print(s.DayOfWeek(2040,6,13))

Golang代码

package main
import "fmt"
func DayOfWeek(year int, month int, day int) string {
	week := []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
	if month < 3 {
		year -= 1
		month += 12
	}
	weekday := (day + 2*month + 3*(month+1)/5 + year + year/4 - year/100 + year/400 + 1) % 7
	return week[weekday]
}
func main() {
	fmt.Println(DayOfWeek(2019, 8, 31))
	fmt.Println(DayOfWeek(1999, 7, 18))
	fmt.Println(DayOfWeek(1993, 8, 15))
	fmt.Println(DayOfWeek(1971, 6, 12))
	fmt.Println(DayOfWeek(2023, 2, 22))
	fmt.Println(DayOfWeek(2040, 6, 13))
}

C++代码

#include<iostream>
using namespace std;
class Solution
{
public:
    string DayOfWeek(int year, int month, int day)
    {
        const char *week[7] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
		if (month < 3) {
		        year -= 1;
		        month += 12;
		    } 
    	int weekday = (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400+1)%7;
	    return week[weekday];
    }
};
int main()
{
	Solution s;
	cout << s.DayOfWeek(2019,8,31) << endl;
	cout << s.DayOfWeek(1999,7,18) << endl;
	cout << s.DayOfWeek(1993,8,15) << endl;
	cout << s.DayOfWeek(1971,6,12) << endl;
	cout << s.DayOfWeek(2023,2,22) << endl;
	cout << s.DayOfWeek(2040,6,13) << endl;
	return 0;
}

使用库函数

Python代码

datetime库

import datetime
class Solution(object):
    def DayOfWeek(self, year, month, day):
        week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
        weekday = datetime.date(year,month,day).isoweekday()
        return week[weekday%7]
if __name__ == "__main__":
    s = Solution()
    print(s.DayOfWeek(2019,8,31))
    print(s.DayOfWeek(1999,7,18))
    print(s.DayOfWeek(1993,8,15))
    print(s.DayOfWeek(1971,6,12))
    print(s.DayOfWeek(2023,2,22))
    print(s.DayOfWeek(2040,6,13))

calendar库 

import calendar
class Solution(object):
    def DayOfWeek(self, year, month, day):
        week = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
        weekday = calendar.weekday(year,month,day)+1
        return week[weekday%7]
if __name__ == "__main__":
    s = Solution()
    print(s.DayOfWeek(2019,8,31))
    print(s.DayOfWeek(1999,7,18))
    print(s.DayOfWeek(1993,8,15))
    print(s.DayOfWeek(1971,6,12))
    print(s.DayOfWeek(2023,2,22))
    print(s.DayOfWeek(2040,6,13))

Golang代码

time库,超级省事,连星期数组都不用了。

package main
import (
	"fmt"
	"time"
)
func DayOfWeek(year int, month int, day int) string {
	return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.Local).Weekday().String()
}
func main() {
	fmt.Println(DayOfWeek(2019, 8, 31))
	fmt.Println(DayOfWeek(1999, 7, 18))
	fmt.Println(DayOfWeek(1993, 8, 15))
	fmt.Println(DayOfWeek(1971, 6, 12))
	fmt.Println(DayOfWeek(2023, 2, 22))
	fmt.Println(DayOfWeek(2040, 6, 13))
}

C++代码

ctime库

#include<iostream>
#include<ctime>
using namespace std;
class Solution
{
public:
    string DayOfWeek(int year, int month, int day)
    {
        const char *week[7] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
	    struct tm t = {0};
	    t.tm_year = year - 1900;
	    t.tm_mon = month - 1;
	    t.tm_mday = day;
	    mktime(&t);
	    return week[t.tm_wday%7];
    }
};
int main()
{
	Solution s;
	cout << s.DayOfWeek(2019,8,31) << endl;
	cout << s.DayOfWeek(1999,7,18) << endl;
	cout << s.DayOfWeek(1993,8,15) << endl;
	cout << s.DayOfWeek(1971,6,12) << endl;
	cout << s.DayOfWeek(2023,2,22) << endl;
	cout << s.DayOfWeek(2040,6,13) << endl;
	return 0;
}

输出:

Saturday
Sunday
Sunday
Saturday
Wednesday
Sunday

--------------------------------
Process exited after 0.02402 seconds with return value 0
请按任意键继续. . .

发现没? 2040.6.13返回的星期是错的!

网上查了资料,原来ctime库的CTime对象是有指定范围的:

static CTime WINAPI GetCurrentTime( );
获取系统当前日期和时间。

返回表示当前日期和时间的CTime对象。
int GetYear( ) const;
获取CTime对象表示时间的年份。

范围从1970年1月1日到2038年1月18日。

时间范围测试:

#include<iostream>
#include<ctime>
using namespace std;
class Solution
{
public:
    string DayOfWeek(int year, int month, int day)
    {
        const char *week[7] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
	    struct tm t = {0};
	    t.tm_year = year - 1900;
	    t.tm_mon = month - 1;
	    t.tm_mday = day;
	    mktime(&t);
	    return week[t.tm_wday%7];
    }
};
int main()
{
	Solution s;
	for (int i=16;i<25;i++)
		cout << i << ":" << s.DayOfWeek(2038,1,i) << endl;
	return 0;
}

测试结果:

16:Saturday
17:Sunday
18:Monday
19:Tuesday
20:Sunday
21:Sunday
22:Sunday
23:Sunday
24:Sunday

--------------------------------
Process exited after 0.05159 seconds with return value 0
请按任意键继续. . .

2038.1.19日的星期也对,之后的全部返回Sunday。

修改这个问题,技术上一点问题都没有。 目前C++都发展到C++20了,而我用的是C++11,暂不知道之后版本的库文件有没有对此问题作过更新。那么,问题来了:

之前用C语言写的的软件,用ctime或者time.h获取时间的软件在2038年1月19日之后都会发生错误。还好,还有整整15年时间来改正这个“时间Bug”。

发表回复