-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0564-find-the-closest-palindrome.cpp
47 lines (43 loc) · 1.18 KB
/
0564-find-the-closest-palindrome.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using ll = long long;
const ll linf = 1e18;
class Solution {
public:
string nearestPalindromic(string n) {
auto pal = [&](ll x) {
string s = to_string(x);
int m = (s.size() - 1) / 2;
for (int i = 0; i <= m; i++) {
s[s.size() - 1 - i] = s[i];
}
return stoll(s);
};
ll nn = stoll(n);
ll left = 0, right = linf;
ll low = 0, high = nn - 1;
while (low <= high) {
ll mid = low + (high - low) / 2;
ll palin = pal(mid);
if (palin < nn) {
left = palin;
low = mid + 1;
} else {
high = mid - 1;
}
}
cout << left;
low = nn + 1, high = linf;
while (low <= high) {
ll mid = low + (high - low) / 2;
ll palin = pal(mid);
if (palin > nn) {
right = palin;
high = mid - 1;
} else {
low = mid + 1;
}
}
cout << right;
if (abs(nn - left) <= abs(nn - right)) return to_string(left);
return to_string(right);
}
};