[leetcode]确定给定日期是星期几——蔡勒公式

题目描述:

给你一个日期,请你设计一个算法来判断它是对应一周中的哪一天。

输入为三个整数:daymonth 和 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"

题目链接:leetcode1185

        为了解决这个问题,我们可以使用蔡勒公式。

        蔡勒公式(Zeller's Congruence)是一种用于计算一个给定日期对应星期几的算法。该公式由德国数学家克里斯蒂安·蔡勒(Christian Zeller)于1882年提出。这个公式可以对公历日期进行计算,但在计算过程中需要一些调整。

蔡勒公式如下:

h = (q + 13*(m+1)//5 + k + k//4 + j//4 -2*j) \mathrm{mod} 7

h星期几的数值
q日期中的日
m日期中的月,1月和2月需要被看作是上一年的13月和14月,即在公式中要加上12
k年份中的年
j世纪数 - 1

通过这个公式,我们可以快速计算给定的日期是星期几。

此外,如果月份是1或2,需要将它们看作是上一年的13月和14月。这就是为什么在公式中要加上12。

代码实现:

# python
def zeller_congruence(day, month, year):
    if month < 3:
        month += 12
        year -= 1


    q = day
    m = month
    K = year % 100
    J = year // 100

    h = (q + 13*(m + 1)//5 + K + K//4 + J//4 - 2*J) % 7

    # Map the result to the corresponding day of the week
    days_of_week = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
    day_of_week = days_of_week[h]

    return day_of_week


day = int(input('day:'))
month = int(input('month:'))
year = int(input('year:'))
result = zeller_congruence(day, month, year)
print(f"The day of the week for {day}/{month}/{year} is: {result}")

运行结果:

day:31
month:12
year:2023
The day of the week for 31/12/2023 is: Sunday

Process finished with exit code 0

由结果可知,2023年12月31日是周日

  • 13
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值