Skip to content

Commit 5bc2957

Browse files
committed
add: 一周中的第几天
1 parent fab2847 commit 5bc2957

File tree

5 files changed

+51
-1
lines changed

5 files changed

+51
-1
lines changed

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -798,3 +798,7 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文
798798
- [参加考试的最大学生数](src/math/maximum_students_taking_exam.cpp) [位运算, 数组, 动态规划, 状态压缩, 矩阵]
799799

800800
- LeetCode 1349. 参加考试的最大学生数 <https://leetcode.cn/problems/maximum-students-taking-exam>
801+
802+
- [一周中的第几天](src/math/day_of_the_week.cpp) [数学]
803+
804+
- LeetCode 1185. 一周中的第几天 <https://leetcode.cn/problems/day-of-the-week>

images/math/day_of_the_week.jpeg

62.6 KB
Loading

src/math/day_of_the_week.cpp

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// 一周中的第几天
2+
// https://leetcode.cn/problems/day-of-the-week
3+
// INLINE ../../images/math/day_of_the_week.jpeg
4+
5+
#include <headers.hpp>
6+
7+
class Solution {
8+
public:
9+
string dayOfTheWeek(int day, int month, int year) {
10+
// 距离 1970 年 12 月 31 日有几天,再加上 3 后对 7 求余
11+
vector<string> week = {"Monday", "Tuesday", "Wednesday", "Thursday",
12+
"Friday", "Saturday", "Sunday"};
13+
vector<int> monthDays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30};
14+
int days = 365 * (year - 1971) + (year - 1969) / 4;
15+
for (int i = 0; i < month - 1; ++i) {
16+
days += monthDays[i];
17+
}
18+
if (((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) && month > 2) {
19+
days += day + 1;
20+
}
21+
days += day;
22+
return week[(days + 3) % 7];
23+
}
24+
};

test/lib/lib_test.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// 执行编译时间:2023-12-29 21:43:59
1+
// 执行编译时间:2023-12-30 13:30:33
22
#include <gtest/gtest.h>
33
#include <lib.hpp>
44

test/math/day_of_the_week_test.cpp

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#include <math/day_of_the_week.cpp>
2+
3+
TEST(一周中的第几天, dayOfTheWeek) {
4+
Solution solution;
5+
// 示例 1:
6+
// 输入:day = 31, month = 8, year = 2019
7+
// 输出:"Saturday"
8+
int day = 31, month = 8, year = 2019;
9+
EXPECT_EQ(solution.dayOfTheWeek(day, month, year), "Saturday");
10+
11+
// 示例 2:
12+
// 输入:day = 18, month = 7, year = 1999
13+
// 输出:"Sunday"
14+
day = 18, month = 7, year = 1999;
15+
EXPECT_EQ(solution.dayOfTheWeek(day, month, year), "Sunday");
16+
17+
// 示例 3:
18+
// 输入:day = 15, month = 8, year = 1993
19+
// 输出:"Sunday"
20+
day = 15, month = 8, year = 1993;
21+
EXPECT_EQ(solution.dayOfTheWeek(day, month, year), "Sunday");
22+
}

0 commit comments

Comments
 (0)