题目描述
2020 年春节期间,有一个特殊的日期引起了大家的注意:2020 年 2 月 2 日。因为如果将这个日期按 “yyyymmdd” 的格式写成一个 8 位数是 20200202,恰好是一个回文数。我们称这样的日期是回文日期。
有人表示 20200202 是 “千年一遇” 的特殊日子。对此小明很不认同,因为不到 2 年之后就是下一个回文日期:20211202 即 2021 年 12 月 2 日。
也有人表示 20200202 并不仅仅是一个回文日期,还是一个 ABABBABA 型的回文日期。对此小明也不认同,因为大约 100 年后就能遇到下一个 ABABBABA 型的回文日期:21211212 即 2121 年 12 月 12 日。算不上 “千年一遇”,顶多算 “千年两遇”。
给定一个 8 位数的日期,请你计算该日期之后下一个回文日期和下一个 ABABBABA 型的回文日期各是哪一天。
输入描述
输入包含一个八位整数 N,表示日期。
对于所有评测用例,10000101 ≤ N ≤ 89991231,保证 N 是一个合法日期的 8 位数表示。
输出描述
输出两行,每行 1 个八位数。第一行表示下一个回文日期,第二行表示下一个 ABABBABA 型的回文日期。
输入输出样例
输入
20200202
输出
20211202
21211212
解析
因为是一个八位数日期,年确定后也就是前四位确定了,而要是回文,后四位则是对称的,所以每一年只对应一个回文,依次检查每一年所能构造的回文是否合理(月,日),然后再依次检查每一年是否为ABABBABA型即可。
完整代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int month_day[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
string buildstr(int year);
bool check_rational(const string& s);
bool check_AB(const string& s);
int main()
{
int num;
cin >> num;
int year = num / 10000;
string s = to_string(num);
if (s[0] == s[7] && s[1] == s[6] && s[2] == s[5] && s[3] == s[4])
++year;
int flag = 0; //是否找到下一个回文
while (year) {
if (flag == 0) {
s = buildstr(year);
if (check_rational(s)) {
cout << s << endl;
flag = 1;
}
if (flag == 1 && check_AB(s)) {
cout << s << endl;
break;
}
}
else {
s = buildstr(year);
if (check_rational(s) && check_AB(s)) {
cout << s << endl;
break;
}
}
++year;
}
return 0;
}
string buildstr(int year) {
string s = to_string(year);
string sp = s;
reverse(s.begin(), s.end());
return sp + s;
}
bool check_rational(const string& s) {
int day = (s[6] - '0') * 10 + s[7] - '0';
int month = (s[4] - '0') * 10 + s[5] - '0';
int year = (s[0] - '0') * 1000 + (s[1] - '0') * 100 + (s[2] - '0') * 10 + s[3] - '0';
if (month > 12 || month < 1) return false;
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
month_day[1] = 29;
}
else month_day[1] = 28;
if (day < 1 || day > month_day[month - 1]) return false;
return true;
}
bool check_AB(const string& s) {
if (s[0] == s[2] && s[0] == s[5] && s[0] == s[7] && s[1] == s[3] && s[1] == s[4] && s[1] == s[6])
return true;
return false;
}