Created
October 15, 2021 02:16
-
-
Save yanfeng42/59e81307c694de74901f6074a61a6574 to your computer and use it in GitHub Desktop.
algs4: 1.2.12 使用 蔡勒公式 计算今天星期几
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package life.yanfeng.study.algorithm; | |
import edu.princeton.cs.algs4.StdOut; | |
public class SmartDate { | |
private final int month; | |
private final int day; | |
private final int year; | |
public SmartDate(int m, int d, int y) throws RuntimeException | |
{ | |
// 校验规则, 基于 P56 页首描述的简易规则. | |
if (d < 0 || d > 31) { | |
throw new RuntimeException("illegal day"); | |
} | |
if (m< 0 || m > 15) { | |
throw new RuntimeException("illegal month"); | |
} | |
if (y <= 0) { | |
throw new RuntimeException("illegal year"); | |
} | |
month = m; | |
day = d; | |
year = y; | |
} | |
public int month() { | |
return month; | |
} | |
public int day() { | |
return day; | |
} | |
public int year() { | |
return year; | |
} | |
public String toString() { | |
return month() + "/" + day() + "/" + year(); | |
} | |
public String dayOfTheWeek() { | |
// // "简单" 估算. | |
// int days = month * 31 + year * 365 + day; | |
// switch (days % 7) { | |
// case 1: | |
// return "Monday"; | |
// case 2: | |
// return "Tuesday"; | |
// case 3: | |
// return "Wednesday"; | |
// case 4: | |
// return "Thursday"; | |
// case 5: | |
// return "Friday"; | |
// case 6: | |
// return "Saturday"; | |
// case 7: | |
// return "Sunday"; | |
// } | |
// | |
// return ""; | |
// ref: https://zhangjia.io/927.html https://zh.wikipedia.org/wiki/%E8%94%A1%E5%8B%92%E5%85%AC%E5%BC%8F | |
String[] week = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; | |
int y = year; | |
int m = month; | |
int d = day; | |
//如果月份是1月份或者2月份,则看成去一年的13月份和14月份 | |
if (month == 1 || month == 2) { | |
m += 12; | |
y--; | |
} | |
int c = y / 100; //获取年份后两位 | |
y = y % 100; //获取年份后两位 | |
int w = (y + (y / 4) + (c / 4) - (2 * c) + ((26 * (m + 1)) / 10) + d - 1) % 7; | |
w = (w + 7) % 7; | |
return year + "/" + month + "/" + day +": " + week[w]; | |
} | |
public static void main(String[] args) { | |
SmartDate date = new SmartDate(10, 15, 2021); | |
StdOut.println(date.dayOfTheWeek()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
开卷有益.
一直是 借助于 系统方法来判定. 没想到 已经有前辈 总结好 直接计算的公式了.