算法提高 日期计算 时间限制:1.0s 内存限制:256.0MB 问题描述 已知2011年11月11日是星期五,问YYYY年MM月DD日是星期几?注意考虑闰年的情况。尤其是逢百年不闰,逢400年闰的情况。 输入格式 输入只有一行 YYYY MM DD 输出格式 输出只有一行 W 数据规模和约定 1599 <= YYYY <= 2999 1 <= MM <= 12 1 <= DD <= 31,且确保测试样例中YYYY年MM月DD日是一个合理日期 1 <= W <= 7,分别代表周一到周日 样例输入 2011 11 11 样例输出 5
AI 代码解读
c++:
#include<iostream> #include<cstring> #include<cstdio> using namespace std; int a[2][13]={{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}}; bool isRun(int year){//判断是否为闰年 if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0) return true; return false; } int calDay(int year){ int index = 0; if(!isRun(year)) index = 1; int tot = 0; for(int i=1; i<=12; ++i) tot += a[index][i]; return tot; } int Day(int y, int m, int d){//计算从0年0月0日到y年m月d日的时间天数 int ans = 0; for(int i=1; i<y; ++i) ans+=calDay(i); int index = 0; if(!isRun(y)) index = 1; for(int i=1; i<m; ++i) ans += a[index][i]; ans += d; return ans; } int main(){ int y, m, d; cin>>y>>m>>d; int diff = Day(y, m, d) - Day(2011, 11, 11);//已知2011-11-11这一天是星期5 if(diff > 0) cout<<(4+diff%7)%7+1<<endl; else{ for(int i=1; i<=7; ++i) if((i-1 + -diff%7)%7 + 1 == 5){ cout<<i<<endl; break; } } return 0; }
AI 代码解读