题解 | #Day of Week#
Day of Week
https://www.nowcoder.com/practice/a3417270d1c0421587a60b93cdacbca0
#include <iostream> #include <cstdio> #include <string> #include <map> using namespace std; int main() { //数字与星期几的映射 string intToWeekday[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; //月份与int的映射 map<string, int> monthToInt = { {"January", 1}, {"February", 2}, {"March", 3}, {"April", 4}, {"May", 5}, {"June", 6}, {"July", 7}, {"August", 8}, {"September", 9}, {"October", 10}, {"November", 11}, {"December", 12} }; int mDay[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int year, mon, day; char str[100]; string month; bool isBefore; //9 October 2001 //scanf用C风格 while (scanf("%d%s%d", &day, str, &year) != EOF) { month = str;//把字符串从C风格转换成C++风格 mon = monthToInt[month]; //从字符串到整数 //判断是今天以前还是以后 if (year < 2023 || 2023 == year && mon < 2 || 2023 == year && 2 == mon && day < 23) { isBefore = true; } else { isBefore = false; } //从begin走到end int begYear, begMon, begDay, endYear, endMon, endDay; if (isBefore) { begYear = year; begMon = mon; begDay = day; endYear = 2023; endMon = 2; endDay = 23; } else { begYear = 2023; begMon = 2; begDay = 23; endYear = year; endMon = mon; endDay = day; } //算从起点到终点有多少天 int totalDay = 0; while (true) { if (begDay == endDay && begMon == endMon && begYear == endYear) { break; } totalDay++; bool isLeap = begYear % 400 == 0 || begYear % 4 == 0 && begYear % 100 != 0; if (isLeap) { mDay[2] = 29; } else { mDay[2] = 28; } begDay++; if (begDay > mDay[begMon]) { begDay = 1; ++begMon; if (begMon > 12) { begMon = 1; ++begYear; } } } if (isBefore) { printf("%s\n", intToWeekday[(11 - totalDay % 7) % 7 ].c_str()); } else { printf("%s\n", intToWeekday[(totalDay + 4) % 7 ].c_str()); } } }