回文日期
一、枚举回文串 再判断日期是否合法
#include<bits/stdc++.h>
using namespace std;
int monday[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
//判断闰年
bool isyear(int year) {
if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0)
return true;
else return false;
}
bool judge(int date) {
int year, mon, day;
//在8为数字中取出年 月 日
year = date / 10000;
mon = (date%10000)/100;
day = (date % 10000) % 100;
//判断日期是否合法
if (day == 0)
return false;
if (mon != 2 &&day > monday[mon])
return false;
if (mon < 1 || mon>12)
return false;
if (mon == 2) {
if (isyear(year)) {
if (day > monday[2] + 1)
return false;
}
else if (day > monday[2])
return false;
}
return true;
}
int main()
{
int res = 0;
int date1, date2;
cin >> date1 >> date2;
for (int i = 1000; i < 10000; i++) {
int date = i, x = i;
//用四位数字构造8位回文的方法
for (int j = 0; j < 4; j++) {
date = date * 10 + x % 10;
x /= 10;
}
if (date >= date1 && date <= date2) {
if (judge(date)) {
res++;
}
}
}
cout << res << endl;
return 0;
}
二、 自己暴力写的 TLE 只能过一半数据
#include<bits/stdc++.h>
using namespace std;
int ans=0;
bool isyear(int y){
if(y%400==0||y%4==0&&y%100!=0)
return true;
else return false;
}
int get_huiwen(int num){
// int year=0,mon=0,day=0;
// for(int i=0;i<4;i++){
// year=year*10+s[i]-'0';
// }
// for(int i=4;i<=5;i++){
// mon=mon*10+s[i]-'0';
// }
// for(int i=6;i<=7;i++){
// day=day*10+s[i]-'0';
// }
//cout<<year<<' '<<mon<<' '<<day<<endl;
//int num=year*10000+mon*100+day;
int temp=num;
int sum=0;
while(temp){
int n=temp%10;
sum=sum*10+n;
temp/=10;
}
//cout<<num<<' '<<sum<<endl;
if(num==sum)
return 1;
else return 0;
}
int m1[13]={0,31,29,31,30,31,30,31,31,30,31,30,31};
int m2[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int main()
{
string a,b;
cin>>a>>b;
int year1=0,mon1=0,day1=0,year2=0,mon2=0,day2=0;
for(int i=0;i<4;i++){
year1=year1*10+a[i]-'0';
}
for(int i=4;i<=5;i++){
mon1=mon1*10+a[i]-'0';
}
for(int i=6;i<=7;i++){
day1=day1*10+a[i]-'0';
}
for(int i=0;i<4;i++){
year2=year2*10+b[i]-'0';
}
for(int i=4;i<=5;i++){
mon2=mon2*10+b[i]-'0';
}
for(int i=6;i<=7;i++){
day2=day2*10+b[i]-'0';
}
int num1=year1*10000+mon1*100+day1;
int num2=year2*10000+mon2*100+day2;
int nowy=year1,nowm=mon1,nowd=day1;
int numnow=num1;
while(numnow<=num2){
if(get_huiwen(numnow)){
ans++;
}
if(isyear(nowy)){
if(nowm==2){
if(nowd==29){
nowd=1;
nowm++;
}
else nowd++;
}
else if(nowm==1||nowm==3||nowm==5||nowm==7||nowm==8||nowm==10||nowm==12){
if(nowd==31){
nowd=1;
nowm++;
}
else nowd++;
}
else if(nowm==4||nowm==6||nowm==9||nowm==11){
if(nowd==30){
nowd=1;
nowm++;
}
}
}
else{
if(nowm==2){
if(nowd==29){
nowd=1;
nowm++;
}
else nowd++;
}
else if(nowm==1||nowm==3||nowm==5||nowm==7||nowm==8||nowm==10||nowm==12){
if(nowd==31){
nowd=1;
nowm++;
}
else nowd++;
}
else if(nowm==4||nowm==6||nowm==9||nowm==11){
if(nowd==30){
nowd=1;
nowm++;
}
}
}
numnow=nowy*10000+nowm*100+nowd;
}
cout<<ans<<endl;
return 0;
}