题目:回文日期 方法:模拟枚举 题目链接:回文日期 - 蓝桥云课 (lanqiao.cn)
思路:本题的关键是要判断日期的合法性,然后依次枚举,本代码使用三个check,第一个check是判断日期的合法性,第二个check判断日期是否回文,第三个check判断日期是否满足题目要求的特殊形式,每次枚举日期时,我选择用flag来记录只需输出下一个回文,然后再用一个if判断特殊形式,这里不写else if的原因时有可能下一个既是回文又满足特殊情况,所以这时候答案输出是两个相同的回文。
#include <bits/stdc++.h> #define ios \ ios::sync_with_stdio(false); \ cin.tie(nullptr); \ cout.tie(nullptr) #define rep(i,a,n) for(int i=a;i<=n;i++) #define per(i,a,n) for(int i=n;i>=a;i--) #define lowbit(x) ((x) & - (x)) #define pb push_back #define SZ(v) ((int)v.size()) #define PI acos(-1) #define x first #define y second #define mem(a,b) memset((a),(b),sizeof(a)) using namespace std; typedef long long ll; const int INF=0x3f3f3f3f; const ll LLINF=0x3f3f3f3f3f3f3f3fLL; const double eps=1e-6; const int MAX=2e5+10; const ll mod=1e9+7; /********************************* std-head *********************************/ bool isleap(int y) {//判断闰年 return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);//闰年可以被4整除但不能被100整除,或能被400整除。 } bool check(int year, int mouth, int day) {//判断日期是否合法 if (mouth > 12 || mouth == 0)return false; if (day > 31)return false; if (mouth == 2) { if (isleap(year) && day > 29) return false; if (!isleap(year) && day > 28) return false; } if (mouth == 4 || mouth == 6 || mouth == 9 || mouth == 11) if (day > 30)return false; return true; } bool check1(string s) //判断日期是否为回文 { string s1=s; reverse(s.begin(),s.end()); if(s1.compare(s)==0) return true; else return false; } bool check2(string s){ //判断日期是否满足ABABBABA特殊类型 if(check1(s) && s[0]==s[2]&&s[1]==s[3]) return true; else return false; } int main() { int n, i; cin >> n; int year, mouth, day; bool flag = false; for (i = n + 1;i <= 99999999;++i) { year = i / 10000; mouth = i % 10000 / 100; day = i % 100; string str=to_string(i); if(check(year,mouth,day)&&check1(str)&&flag==0) { cout<<str<<endl; flag=1; } if(check(year,mouth,day)&&check1(str)&&check2(str)) { cout<<str<<endl; break; } } return 0; }