寻找最近的回文数cpp代码
时间: 2023-12-04 19:14:00 浏览: 68
求最近素数.cpp
以下是寻找最近的回文数的CPP代码:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool is_palindrome(string s) {
string rev_s = s;
reverse(rev_s.begin(), rev_s.end());
return s == rev_s;
}
int main() {
string s;
cin >> s;
int n = s.length();
bool flag = false;
for (int i = 1; i <= n / 2; i++) {
string left = s.substr(0, i);
string right = s.substr(n - i, i);
if (is_palindrome(left)) {
flag = true;
break;
}
if (is_palindrome(right)) {
flag = true;
break;
}
}
if (flag) {
cout << s << endl;
} else {
string ans = s.substr(0, n / 2);
reverse(ans.begin(), ans.end());
if (n % 2 == 1) {
ans += s[n / 2];
}
ans += s.substr(n / 2, n / 2);
cout << ans << endl;
}
return 0;
}
阅读全文