您的位置:首页 > 其它

HDU 2133 What day is it

2015-11-07 21:21 676 查看
HDU 2133
What day is it
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2133
题目大意:

给出一个日期。求这个日期是星期几?

如果日期格式非法,则输出  ”illegal“ 。

 

有一个公式叫蔡勒公式,但是运算结果有差错,我不知道是不是我计算有问题,这里不做讨论。

另外一种暴力的方法就是计算出该日期距离0001年1月1日(星期一)的总天数,然后MOD7就可以得出。

总天数 = (年份-1)*365 + 闰年的数目 + (月份-1)的总天数 + 该月天数。

还有一个就是判断日期的合法性,要注意闰年2月的判断。

 

总的来说,题目不难,但是考验写简单代码的功底。

AC代码:

#include <iostream>

using namespace std;

int days[15]={0,31,28,31,30,31,30,31,31,30,31,30,31};

///判断是不是闰年
int IsLeap(int Y)
{
if((Y%4 == 0 && Y % 100 != 0)||(Y % 400 == 0)) { ///如果是闰年
return 1;
} else { ///如果不是闰年
return 0;
}

}

///判断数据是否合法
int judge(int Y,int M,int D)
{
if(Y > 0 && Y < 10000 &&
M > 0 && M < 13 &&
D > 0) { ///数据合法性判断
if(2 == M) { ///闰年的二月单独判断
return D <= days[2]+IsLeap(Y);
}else{
return D <= days[M];
}
} else {
return 0;
}
}

///计算总天数
int totday(int Y,int M,int D)
{
int ret = 0;
for(int i = 1; i < Y; i++){
ret += 365 + IsLeap(i);
}

days[2] += IsLeap(Y); ///如果是闰月,二月+1

for(int i = 1; i < M;i++){
ret += days[i];
}

days[2] = 28;///恢复原来的二月

return ret + D;
}

int main()
{
int year = 0;
int month = 0;
int day = 0;

while(cin>>year>>month>>day) {
if(0 == judge(year,month,day)) {
cout<<"illegal"<<endl;
} else {
switch(totday(year, month, day)%7) {
case 1:
cout<<"Monday"<<endl;
break;
case 2:
cout<<"Tuesday"<<endl;
break;
case 3:
cout<<"Wednesday"<<endl;
break;
case 4:
cout<<"Thursday"<<endl;
break;
case 5:
cout<<"Friday"<<endl;
break;
case 6:
cout<<"Saturday"<<endl;
break;
case 0:
cout<<"Sunday"<<endl;
break;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: