枚举合法日期:
#include <bits/stdc++.h>
using namespace std;
int month[13] = {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int date, ans1, ans2;
// 判断日期是否为回文
bool check1(int date) {
string s = to_string(date);
if (s[0] == s[7] && s[1] == s[6] && s[2] == s[5] && s[3] == s[4])
return true;
return false;
}
// 判断日期是否满足 ABABBABA 型回文
bool check2(int date) {
string s = to_string(date);
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;
}
signed main() {
cin >> date;
int y = date / 10000, m = date / 100 % 100, d = date % 100;
for (int i = y;; i++) {
if (i % 400 == 0 || (i % 100 != 0 && i % 4 == 0))
month[2] = 29;
else
month[2] = 28;
int j = (i == y) ? m : 1;
for (; j <= 12; j++) {
int k = (i == y && j == m) ? d + 1 : 1;
for (; k <= month[j]; k++) {
int new_date = i * 10000 + j * 100 + k;
if (check1(new_date) && ans1 == 0)
ans1 = new_date;
if (check2(new_date)) {
cout << ans1 << '\n' << new_date << '\n';
return 0; // 当找到了 ABABBABA 型回文日期时,结束程序
}
}
}
}
return 0;
}
枚举年份:
#include <bits/stdc++.h>
using namespace std;
// month[1~12]分别记录1~12月每月的天数
int date, month[13] = {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 判断日期是否合法
string check(int date) {
string s = to_string(date), t = to_string(date); // 将整型转换为字符串
reverse(t.begin(), t.end()); // 翻转
s += t; // 将s翻转后再与s拼接,拼接后的字符串一定会是个回文串
int y = stoi(s.substr(0, 4)), m = stoi(s.substr(4, 2)), d = stoi(s.substr(6, 2));
if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))
month[2] = 29;
else
month[2] = 28;
if (m < 1 || m > 12 || d < 1 || d > month[m])
return "-1";
return s;
}
// 判断日期是否是ABABBABA型回文
string check2(int date) {
string s = to_string(date), t = to_string(date);
reverse(t.begin(), t.end()); // 翻转
s += t;
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 s;
return "-1";
}
signed main() {
cin >> date;
string ans1 = "";
for (int i = date / 10000;; i++) {
// 注意:date(输入的日期)不能作为答案
if (check(i) == "-1" || check(i) == to_string(date)) continue;
if (ans1 == "") ans1 = check(i);
if (check2(i) != "-1") {
cout << ans1 << '\n' << check2(i) << '\n';
return 0;
}
}
return 0;
}
以上就是这次博客的内容了
别忘了请点个赞+收藏+关注支持一下博主喵!!!
关注博主,更多蓝桥杯nice题目静待更新:)