【蓝桥杯】(完全日期)
完全日期
#include <iostream>
using namespace std;
int main()
{
int ans=0;
//2001 1 1 //2021 12 31
int monthday[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
for(int year=2001;year<=2021;year++)
{
monthday[2]=28;
if((year%4==0&&year%100!=0)||year%400==0)
monthday[2]=29;
int cnt1=0;
int tmp=year;
while(tmp)
{
// tmp%=10;
cnt1+=tmp%10;
tmp/=10;
}
for(int month=1;month<=12;month++)
{
for(int day=1;day<=monthday[month];day++)
{
int cnt2=month/10+month%10;
int cnt3=day/10+day%10;
int cnt=cnt1+cnt2+cnt3;
if(cnt==9||cnt==16||cnt==25)
ans++;
}
}
}
cout<<ans;
// 请在此输入您的代码
return 0;
}
错误版本(只处理个位数):
tmp = 2021; // 初始值为年份2021
// 第一次循环
tmp %= 10; // tmp = 2021 % 10 = 1
cnt1 += tmp; // cnt1 = 0 + 1 = 1
tmp /= 10; // tmp = 1 / 10 = 0 (向下取整)
// 第二次及后续循环,因tmp已变为0,循环终止
在这个例子中,错误版本的代码只处理了年份2021
的个位数1
,并将1
累加到cnt1
。由于tmp
在第一次循环后被除以10后变为0
,循环不再继续,因此cnt1
最终只包含了年份的个位数之和,即1
。
正确版本(递归处理所有位数):
tmp = 2021; // 初始值为年份2021
// 第一次循环
cnt1 += tmp % 10; // cnt1 = 0 + 1 = 1
tmp /= 10; // tmp = 2021 / 10 = 202 (向下取整)
// 第二次循环
cnt1 += tmp % 10; // cnt1 = 1 + 2 = 3
tmp /= 10; // tmp = 202 / 10 = 20 (向下取整)
// 第三次循环
cnt1 += tmp % 10; // cnt1 = 3 + 0 = 3
tmp /= 10; // tmp = 20 / 10 = 2 (向下取整)
// 第四次循环
cnt1 += tmp % 10; // cnt1 = 3 + 2 = 5
tmp /= 10; // tmp = 2 / 10 = 0 (向下取整)
// 第五次及后续循环,因tmp已变为0,循环终止
原文地址:https://blog.csdn.net/2301_76518242/article/details/137681126
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!