第十一届蓝桥杯c++B组第二场第四题
emm…经典处理日期的问题,开一个月份M数组即可
方法一:
#include<iostream>
using namespace std;
int y = 2000,m = 1,d = 1,w = 6,ans = 2; //定义年,月,日,星期w
int M[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int main()
{
while(y != 2020 || m != 10 || d != 1)
{
if((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) M[2] = 29;
else M[2] = 28; //这里else不能丢,因为要保证每一年都要更新M[2]
d++;
w = (w + 1) % 7;
if(d>M[m])
{
d = 1;
m++;
if(m > 12)
{
m = 1;
y++;
}
}
if(d == 1 || w == 1) ans++;
ans++;
}
cout<<ans;
return 0;
}
方法二:
#include<iostream>
using namespace std;
typedef long long LL;
LL res,Monday;
int days[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
bool is_vaild(int x)
{
int yy = x/10000,mm = x%10000/100,day = x%100;
if(mm < 1 || mm > 12) return false;
if(day <= 0) return false;
if(mm != 2)
{
if(day > days[mm]) return false;
}
else
{
int leap =((yy % 4 == 0 && yy % 100 != 0) || (yy % 400 == 0));
if(day > 28 + leap) return false;
}
return true;
}
int main()
{
int w = 5;
for(int i = 20000101;i <= 20201001;i++)
{
int yy = i/10000,mm = i%10000/100,dd = i%100;
if(!is_vaild(i)) continue; //一定要先判断日期是否合法再进行星期的变换,不然星期会乱套!!!
else //(ps:这个细节看了我三天硬是没找出来,一直是8877少答案2,低级错误)
{
w = (w + 1) % 7;
if(dd == 1 || w == 1) res++;
res++;
}
}
cout<<res;
}
求关注