1185. 一周中的第几天

1185. 一周中的第几天层

解法一: 按年份一次计算

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func dayOfTheWeek(day int, month int, year int) string {
daySum := 0
for i := 1970; i < year; i++ {
if isLeep(i) {
daySum += 366
} else {
daySum += 365
}
}
months := []int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
for i := 1; i < month; i++ {
daySum += months[i - 1]
}
if month > 2 && isLeep(year) {
daySum++
}
daySum += day
days := []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
return days[(daySum + 3) % 7]
}

func isLeep(year int) bool {
return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))
}

解法二: 日期工具类

java
1
2
3
4
5
6
7
class Solution {
public String dayOfTheWeek(int day, int month, int year) {
String[] weeks = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
LocalDate date = LocalDate.of(year, month, day);
return weeks[date.getDayOfWeek().getValue() - 1];
}
}
作者

wuhunyu

发布于

2023-12-30

更新于

2023-12-30

许可协议