(前置知识)非闰年的每月天数打表:
int day[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
一、判断日期是否合法
bool check(int y,int m,int d)
{if(!d||!m||m>12)return false;if(m!=2){if(d>day[m])return false;}else{int idx=((y%100!=0&&y%4==0)||y%400==0);if(d>day[m]+idx)return false;}return true;
}
二、判断某年某月的天数
int get(int y,int m)
{int flag=((y%4==0&&y%100!=0)||y%400==0);if(m!=2)return day[m];else{return day[m]+flag;}
}
三、制造日期回文数
例题:acwing-466. 回文日期
#include<bits/stdc++.h>
using namespace std;
int day[13]={0,31,29,31,30,31,30,31,31,30,31,30,31};
bool check(int y,int m,int d)//检查日期合法性
{if(!d||!m||m>12)return false;if(m!=2){if(d>day[m])return false;}else{int idx=((y%100!=0&&y%4==0)||y%400==0);if(d>28+idx)return false;}return true;
}
int main()
{int a,b,x;cin>>a>>b;int sum=0;for(int i=1;i<13;i++){for(int j=1;j<=day[i];j++){x=(j%10*1000+j/10*100+i%10*10+i/10);//已经确定了日和月,因为回文就确定了年x=x*10000+i*100+j;//年+月+日if(x>=a&&x<=b&&check(x/10000,i,j))sum++;}}cout<<sum<<endl;return 0;
}
四、给定年月日,求n天后的日期
例题:acwing-3607.打印日期
#include<bits/stdc++.h>
using namespace std;
int day[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
void get(int y)//判断润不润
{if(((y%4==0)&&y%100!=0)||y%400==0){day[2]=29;}
}
int main()
{int y,n;while(cin>>y>>n){day[2]=28;get(y);int m=0,d=0;while(n--){d++;if(d>day[m]){m++;d=1;}if(m>12){y++;m=1;}}printf("%04d-%02d-%02d\n",y,m,d);}return 0;
}
五、某两天相隔天数
#include<bits/stdc++.h>
using namespace std;
int day[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int get(int y,int m)
{int flag=((y%4==0&&y%100!=0)||y%400==0);if(m!=2)return day[m];else{return 28+flag;}
}
int main()
{int ans=0;int y1,m1,d1;int y2,m2,d2;cin>>y1>>m1>>d1;cin>>y2>>m2>>d2;while(1){ans++;d1++;if(d1>get(y1,m1)){m1++;d1=1;}if(m1>12){y1++;m1=1;}if(y1==y2&&m1==m2&&d1==d2){cout<<ans;return 0;}}
}