File tree 1 file changed +30
-0
lines changed
1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(l)
2
+ // Space: O(l)
3
+
4
+ class Solution {
5
+ public:
6
+ string nearestPalindromic (string n) {
7
+ const auto l = n.size ();
8
+ vector<long long > candidates;
9
+ candidates.emplace_back (static_cast <long long >(pow (10 , l)) + 1 );
10
+ candidates.emplace_back (static_cast <long long >(pow (10 , l - 1 )) - 1 );
11
+ auto prefix = stol (n.substr (0 , (l + 1 ) / 2 ));
12
+ for (long long i = -1 ; i <= 1 ; ++i) {
13
+ auto p = to_string (prefix + i);
14
+ auto pp = p + string (p.rbegin () + (l % 2 ), p.rend ());
15
+ candidates.emplace_back (stol (pp));
16
+ }
17
+ long long num = stol (n), closest_val = numeric_limits<long long >::max ();
18
+ for (const auto & val : candidates) {
19
+ if (val == num) {
20
+ continue ;
21
+ }
22
+ if (abs (val - num) < abs (closest_val - num)) {
23
+ closest_val = val;
24
+ } else if (abs (val - num) == abs (closest_val - num)) {
25
+ closest_val = min (closest_val, val);
26
+ }
27
+ }
28
+ return to_string (closest_val);
29
+ }
30
+ };
You can’t perform that action at this time.
0 commit comments