forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
26 lines (25 loc) · 827 Bytes
/
Solution.cpp
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
class Solution {
public:
string nearestPalindromic(string n) {
long x = stol(n);
long ans = -1;
for (long t : get(n))
if (ans == -1 || abs(t - x) < abs(ans - x) || (abs(t - x) == abs(ans - x) && t < ans))
ans = t;
return to_string(ans);
}
unordered_set<long> get(string& n) {
int l = n.size();
unordered_set<long> res;
res.insert((long) pow(10, l - 1) - 1);
res.insert((long) pow(10, l) + 1);
long left = stol(n.substr(0, (l + 1) / 2));
for (long i = left - 1; i <= left + 1; ++i) {
string prefix = to_string(i);
string t = prefix + string(prefix.rbegin() + (l & 1), prefix.rend());
res.insert(stol(t));
}
res.erase(stol(n));
return res;
}
};