这道题不能用暴力枚举所有数字来求解,因为部分答案会超时。我们可以直接枚举回文数字,因为这题只用判断是否是回文日期,我们可以直接枚举回文数的前四位,后四位可以用前四位得到,然后再分别判断是否满足日期要求即可。
#include <bits/stdc++.h> using namespace std; //判断是否是日期 bool check(int s) { int year = s / 10000, month = s % 10000 / 100, day = s % 100; int nums[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //判断除二月以外的日期 if (month != 2 && (month == 0 || month > 12 || day == 0 || nums[month] < day)) return false; //判断二月 int leap = (year % 100 && year % 4 == 0) || year % 400 == 0; if (month == 2 && (day == 0 || nums[2] + leap < day)) return false; return true; } //判断是否是回文日期 bool check1(string x) { return x[0] == x[7] && x[1] == x[6] && x[2] == x[5] && x[3] == x[4]; } //判断是否是ABABBABA型回文日期 bool check2(string x) { return x[0] != x[1] && x[0] == x[5] && x[0] == x[7] && x[0] == x[2] && x[1] == x[3] && x[1] == x[4] && x[1] == x[6]; } //将整数转换成字符串 string tostring(int x) { string num = ""; while (x) { char k = x % 10 + '0'; num = k + num; x /= 10; } return num; } int main() { int n, flag1 = 0, flag2 = 0; string ans1, ans2; cin >> n; n = n / 10000; //枚举所有回文数 for (int i = n ; i <= 9999; i++) { int date = i, x = i; while (x) { date = date * 10 + x % 10; x /= 10; } string res = tostring(date); if (flag1 == 0 && check(date) && check1(res)) { ans1 = res; flag1 = 1; } if (flag2 == 0 && check(date) && check2(res)) { ans2 = res; flag2 = 1; } if (flag1 == 1 && flag2 == 1) break; } cout << ans1 << endl; cout << ans2 << endl; return 0; }