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.
方法1:
discussion:https://leetcode.com/problems/find-the-closest-palindrome/discuss/102391/python-simple-with-explanation
grandyang:https://www.cnblogs.com/grandyang/p/6915355.html
思路:
一共只需要比较5个候选者。首先假设给定n的位数是 len,那么候选数字如果和n位数不同,只能是99…999 , 10…01这种形式。比如对于一个三位数,左右边界为[99, 1001],先把这两个数字放进candidates set中。然后考虑和n数位相同的情况,首先确定要改动一定先改动右边,因为这样造成的差值最小。所以相当于左半边翻转然后连接,这里用string(left.rbegin() + (len & 1), left.rend());的写法,也就是len为奇数的情况下复制除了中轴,偶数复制全部。剩下的三个candidates分别是prefix - 1, +0, +1的情况。用prefix = 234来举例,candidates循环中产生23332, 23432, 23532三个候选。最后由于要避免n本身就是palindrome的情况,要将它本身从candidates中删除。最后通过比较和原数字大小来决定最终结果,注意如果差值相同时优先选择较小值。
易错点
- 删除n本身。
- 如果差值相同时优先选择较小值。
- (len & 1)。
class Solution {
public:
string nearestPalindromic(string n) {
int len = n.size();
set<long> candidates;
candidates.insert(pow(10, len) + 1);
candidates.insert(pow(10, len - 1) - 1);
long prefix = stol(n.substr(0, (len + 1) / 2));
for (int i = -1; i <= 1; i++) {
string left = to_string(prefix + i);
string rest = string(left.rbegin() + (len & 1), left.rend());
candidates.insert(stol(left + rest));
}
candidates.erase(stol(n));
long num = stol(n), minDiff = LONG_MAX, result;
for (auto a: candidates) {
long diff = abs(a - num);
if (diff < minDiff) {
result = a;
minDiff = abs(a - num);
}
else if (diff == minDiff){
result = min(a, result);
}
}
return to_string(result);
}
};