# 564. Find the Closest Palindrome

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.

``````class Solution {
public:
string nearestPalindromic(string n) {
long len = n.size(), num = stol(n), res, minDiff = LONG_MAX;
unordered_set<long> s;
s.insert(pow(10, len) + 1);
s.insert(pow(10, len - 1) - 1);
long prefix = stol(n.substr(0, (len + 1) / 2));
for (long i = -1; i <= 1; ++i) {
string pre = to_string(prefix + i);
string str = pre + string(pre.rbegin() + (len & 1), pre.rend());
s.insert(stol(str));
}
s.erase(num);
for (auto a : s) {
long diff = abs(a - num);
if (diff < minDiff) {
minDiff = diff;
res = a;
} else if (diff == minDiff) {
res = min(res, a);
}
}
}
};
``````

https://discuss.leetcode.com/topic/88897/java-solution-with-detailed-proof

https://discuss.leetcode.com/topic/87271/c-short-solution-only-need-to-compare-5-numbers

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation