求Hackerrank星期计算题更优解法及C++代码改进建议
题目求助
我是竞技编程新手,过去一小时左右一直在尝试解决这道挑战题。我确信自己的解法过于复杂冗余,恳请大家提供更优的解题方案,同时也请各位对我编写的代码给出改进反馈。
题目描述
给定某月第一天对应的星期值M(取值规则:1代表周一,2代表周二,3代表周三……7代表周日),以及当月的一个日期D,要求计算该日期D对应的星期值。
约束条件
- 1 ≤ M ≤ 7
- 1 ≤ D ≤ 31
示例
- 输入:
1 30 - 输出:
2
待改进的原有代码
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int find_answer_for_more_than_7_days(int start,int day){ cout<<day%7 + start - 1; return 0; } int find_answer_for_less_than_7_days(int start,int day){ if ((start + day - 1)>7) cout<<start+day - 8; else cout<< start + day - 1; return 0; } int find_answer(int start, int day){ if (day>7) find_answer_for_more_than_7_days(start, day); else if (day<7) find_answer_for_less_than_7_days(start,day); return 0; } int main() { int m,d; cin>>m>>d; if (d!=1){ if (d%7 == 0){ if (m != 1) cout<<m-1; else cout<<7; } else{ if (m == 1){ if (d>7) cout<<d%7; else if (d<7) cout<< d; } else if (m == 7){ if (d > 7) cout<<d - 7*(d/7) - 1; else if (d< 7) cout<< d - 1; } else{ find_answer(m,d); } } } else cout<< m; return 0; }
解答
原有代码的问题
- 逻辑拆分过度:把简单的周期计算拆成了d=1、d%7==0、m=1、m=7、d>7、d<7等无数特殊分支,代码冗余度极高,还很容易出bug——比如
find_answer函数只判断了day>7和day<7,完全漏掉了day==7的场景,输入d=7时这个分支根本不会有输出。 - 头文件冗余:引入了
<cmath>、<cstdio>、<vector>、<algorithm>四个完全没用到的头文件,没有实际意义。 - 函数拆分不合理:三个自定义函数本质都是在做星期偏移计算,完全没必要拆成多个函数写重复逻辑。
最优解题思路
星期是固定7天循环的周期问题,根本不需要分任何特殊情况,用统一的取模公式就能覆盖所有输入场景:
- 先把1~7的星期值转成0基计数(0代表周一,6代表周日),避免取模后出现0值需要额外判断的问题,初始星期的0基值为
M-1 - 1号到D号的间隔天数是
D-1天,总偏移量为(M-1) + (D-1) - 总偏移量对7取模得到D号的0基星期值,再加1转回题目要求的1~7计数即可
精简后的正确代码
#include <iostream> using namespace std; int main() { int m, d; cin >> m >> d; cout << (m - 2 + d) % 7 + 1 << endl; return 0; }
用题目给的示例验证:输入m=1、d=30,代入公式得(1-2+30) %7 +1 =29%7 +1=1+1=2,和示例输出完全一致。所有边界场景比如m=7、d=1、d=7、d=31都能直接计算正确,不需要任何额外分支判断,不会出现漏判边界的问题。
内容的提问来源于stack exchange,提问作者Konos
相关产品推荐
相关产品推荐

