题目描述:
Given an integer n, find the closest integer (not including itself), which is a palindrome.
The 'closest' is defined as absolute difference minimized between two integers.
Example 1:
Input: "123"
Output: "121"
Note:
1. The input n is a positive integer represented by string, whose length will not exceed 18.
2. If there is a tie, return the smaller one as answer.
需要找和目标值最接近的回文数,那么其实只需要考虑五个数即可。首先是上界和下界,根据目标值的位数可以确定,然后截取目标数的前半段得到half_num,分别加上-1,0,1,再凑成回文数,之后再判断这五个数中到底哪个是最接近目标值的回文数。
class Solution {
public:
string nearestPalindromic(string n) {
//假设n="12345"
int len=n.size();
unordered_set<long long> s;
long long a=pow(10,len)+1; //a=100001,上界
long long b=pow(10,len-1)-1; //b=9999,下界
s.insert(a);
s.insert(b);
long long num=stoll(n);
string half=n.substr(0,(len+1)/2); //half="123"
long long half_num=stoll(half);
for(int i=-1;i<=1;i++)
{ //分别得到12221,12321,12421
long long left_num=half_num+i;
string left=to_string(left_num);
string right=left;
reverse(right.begin(),right.end());
if(len%2==0) s.insert(stoll(left+right));
else s.insert(stoll(left+right.substr(1)));
}
s.erase(num);//如果n本身为回文数,产生的五个数中会包含它本身,需要删除
long long min_diff=LONG_LONG_MAX;
long long result=0;
for(auto x:s)
{
if(abs(x-num)==min_diff&&x<num) result=x;
else if(abs(x-num)<min_diff)
{
result=x;
min_diff=abs(x-num);
}
}
return to_string(result);
}
};