思路:
本题的思路,首先肯定得暴力遍历每一个大于给出的年份,然后判断该年份是否满足要求。
观察题目我们可以知道要求的ABABBABA型的回文串,可以知道后面的月和日跟年有关,也就是一年只有可能有一个回文串。因此我们只需要遍历年,然后将年翻转接到年后边形成一个新字符串,然后判断是否符合年月日的规范就可以了。
该题使用到的函数:
1、stoi函数
1)功能:将字符串转换成十进制。
2)函数的使用:
#include<iostream>
using namespace std;
int main() {
string str = "123456";//定义字符串
//该函数有俩种调用方式
int t1 = stoi(str,0,8);//将字符串 str 从 0 位置之后的数字的 2 进制数,转换为十进制
cout<<t1<<' ';
int t2 = stoi(str);//将整个字符串转换为十进制
cout<<t2<<endl;
return 0;
}
输出:42798 123456
2、substr函数
1) 功能:取字符串的子串。
2)函数的使用:
#include<bits/stdc++.h>
using namespace std;
int main() {
string str = "123456";//定义字符串
string s1 = str.substr(0,3);//从第一个字符开始往后取三个字符
cout<<s1<<endl;
return 0;
}
输出:123
3、to_string 函数
1)功能:将数值转化为字符串。返回对应的字符串。
2) 函数的使用:
#include<bits/stdc++.h>
using namespace std;
int main() {
string s1 = to_string(123456)+"hello";
cout<<s1<<endl;
return 0;
}
输出:123456hello
题解:
#include<bits/stdc++.h>
using namespace std;
int D[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};//日期数组
bool ok(string s){//判断是否回文
if(s[0] = s[2]&&s[2] ==s[5]&&s[5] == s[7]&&s[1] == s[3]&&s[3] == s[4]&&s[4]==s[6]&&s[0]!=s[1]){
return 1;
}
return 0;
}
bool check(int y){//判断是否闰年
if(y%400 == 0 || (y%4 == 0&&y&100 != 0)){
return 1;
}
return 0;
}
int main()
{
string s,s1 = "",s2 = "";
cin>>s;
for(int i = stoi(s.substr(0,4));s1==""||s2=="";i++){//遍历年,直到找到俩个回文字符串
string temp1 = to_string(i),temp2 = to_string(i);//提取年然后将反转构成回文串
reverse(temp2.begin(),temp2.end()); //反转
temp1+=temp2; //构造回文串
if(temp1<=s) continue; //要求在s的后面找
//提取年月日
int y = stoi(s.substr(0,4)), m = stoi(s.substr(4,2)),d = stoi(s.substr(6,2));
if(check(y)) D[2] = 29;//修改该年二月份的天数
else D[2] = 28;
//当不符合要求时判断下一个年份
if(m<0||m>12) continue;
if(d<0||d>D[m]) continue;
if(s1 == "") s1 = temp1;
if(ok(temp1)&&s2 == "") s2 = temp1;
}
cout<<s1<<endl<<s2<<endl;
return 0;
}