Find The Closest Palindrome Problem
Description
LeetCode Problem 564.
Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.
The closest is defined as the absolute difference minimized between two integers.
Example 1:
1
2
Input: n = "123"
Output: "121"
Example 2:
1
2
3
Input: n = "1"
Output: "0"
Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.
Constraints:
- 1 <= n.length <= 18
- n consists of only digits.
- n does not have leading zeros.
- n is representing an integer in the range [1, 10^18 - 1].
Sample C++ Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
string makePalindromic(string s) {
for (int i = 0, j = (int)s.length() - 1; i < j; i++, j--)
s[j] = s[i];
return s;
}
string nearestPalindromic(string n) {
if (n == "0")
return "1";
long long orgVal = stoll(n);
// candidate #1 (ex: 123xx -> 12321, 123xxx -> 123321)
string res = makePalindromic(n);
long long resVal = stoll(res);
long long diff = abs(resVal - orgVal);
long long scale = (long long)pow(10, (int)n.length() / 2);
// candidate #2 (ex: 123xx -> 12221, 123xxx -> 122221, 100xx -> 9999)
string smaller = makePalindromic(to_string((orgVal / scale) * scale - 1));
// candidate #3 (ex: 123xx -> 12421, 123xxx -> 124421, 99xx -> 10001)
string bigger = makePalindromic(to_string((orgVal / scale) * scale + scale));
long long smallerVal = stoll(smaller);
if (diff == 0 || abs(orgVal - smallerVal) <= diff) {
res = smaller;
diff = abs(orgVal - smallerVal);
}
long long biggerVal = stoll(bigger);
if (abs(orgVal - biggerVal) < diff)
res = bigger;
return res;
}
};