题目:
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:
- The input n is a positive integer represented by string, whose length will not exceed 18.
- If there is a tie, return the smaller one as answer.
思路:
和n最接近的回文数根据位数划分,则只有3种可能:
1:比n多1位的数,例如对于99而言,距离它最近的回文数就是101;
2:比n少1位的数,例如对于101, 距离它最近的回文数就是99;
3:和n位数一样,并且其后一半是n的前一半的翻转的数。这样的数又可以分为3种:1)中间数和n相同的,例如123的最近回文数就是121;2)中间数比n大1,例如189的最近回文数就是191;3)中间数比n小1,例如920的最近回文数就是919。
所以只要把这5个数分别计算出来,然后比较哪一个和n最接近即可。
代码:
class Solution {
public:
string nearestPalindromic(string n) {
int l = n.size();
set<long> candidates;
// biggest, one more digit, 10...01
candidates.insert(long(pow(10, l)) + 1);
// smallest, one less digit, 9...9 or 0
candidates.insert(long(pow(10, l - 1)) - 1);
// the closest must be in middle digit +1, 0, -1, then flip left to right
long prefix = stol(n.substr(0, (l + 1) / 2));
for ( long i = -1; i <= 1; ++i ) {
string p = to_string(prefix + i);
string pp = p + string(p.rbegin() + (l & 1), p.rend());
candidates.insert(stol(pp));
}
long num = stol(n), minDiff = LONG_MAX, diff, minVal;
candidates.erase(num); // cannot be itself
for ( long val : candidates ) {
diff = abs(val - num);
if ( diff < minDiff ) {
minDiff = diff;
minVal = val;
}
}
return to_string(minVal);
}
};