试题 B: 含2天数
本题总分:5 分
【问题描述】
小蓝特别喜欢 2,今年是公元 2020 年,他特别高兴,因为每天日历上都可以看到 2。如果日历中只显示年月日,请问从公元 1900 年 1 月 1 日到公元 9999 年 12月 31 日,一共有多少天日历上包含 2。即有多少天中年月日的数位中包含数字2。
【答案提交】
这是一道结果填空的题,你只需要算出结果后提交即可。本题的结果为一个整数,在提交答案时只填写这个整数,填写多余的内容将无法得分。
解析
- 区分闰年和平年
闰年的判断:
①整百年数除以400,无余为闰,有余为平
②非整百年数除以4,无余为闰,有余为平
- 依次按照判断哪些年份、月份、号数含有2
- 若年份中含有2,则直接判断该年总的天数(注意平年和闰年2月天数不同)
- 若年份中不含有2,实际只需判断2月和12月一共有多少天(注意平年和闰年2月天数不同),其中12月一共有31天。
- 若年份中不含有2,且月份中不含有2,即判断1、3、4、5、6、7、8、9、10、11这10个月中的号数一共有多少天含有2,这10个月的一共含有2的天数是固定的,即10*12天 = 120天。
答案:1994240
程序
#include <bits/stdc++.h>
using namespace std;
//判断年份y中是否含有2,如1902、2221都含有2
bool isInclude2(int y){
while(y){
if((y%10) == 2) return(true);
y /= 10;
}
return false;
}
//判断某年是否为闰年
bool isLeap(int y){
//整百年数除以400,无余为闰,有余为平
if((y%100==0) && (y%400==0)) return true;
//非整百年数除以4,无余为闰,有余为平
if((y%100!=0) && (y%4==0)) return true;
return false;
}
int main()
{
int startYear = 1900; //起始年份
int endYear = 9999; //结束年份
int numOneYear = 0; //记录某年中含有2的天数
int totals = 0; //记录总的含有2的天数
int numTenMonths = 120; //1、3、4、5、6、7、8、9、10、11这10个月
//一共含有2的天数是固定的,即10*12天 = 120天
int num12Month = 31; //12月含有的天数
for(int y=startYear; y<=endYear; y++){
//判断该年份是否含有2
if(isInclude2(y)) {
//判断是闰年还是平年
if(isLeap(y)) numOneYear = 366;
else numOneYear = 365;
}else {
if(isLeap(y)){
//是闰年则2月份为29天
numOneYear = num12Month + numTenMonths + 29;
}else{
//是平年则2月份为28天
numOneYear = num12Month + numTenMonths + 28;
}
}
totals += numOneYear;
}
cout << "totals = " << totals << endl;
return 0;
}
结果
yocin@ubuntu:~/Documents/cppPractice$ ./main
totals = 1994240