File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ string nearestPalindromic(string n) {
4+ if(n.length()==1)
5+ return to_string(stoi(n)-1);
6+
7+ int d = n.length();
8+ vector<long> candidates;
9+ candidates.push_back(pow(10,d-1)-1);
10+ candidates.push_back(pow(10,d)+1);
11+
12+ int mid = (d+1)/2;
13+ long prefix = stol(n.substr(0,mid));
14+ vector<long> v = {prefix,prefix+1, prefix-1};
15+ for(long i : v)
16+ {
17+ string postfix = to_string(i);
18+ if(d%2!=0)
19+ postfix.pop_back();
20+ reverse(postfix.begin(), postfix.end());
21+ string c = to_string(i)+postfix;
22+ candidates.push_back(stol(c));
23+ }
24+ long mindiff = LONG_MAX;
25+ long result;
26+ long num = stol(n);
27+ for(int i=0;i<5;i++)
28+ {
29+ if(candidates[i]!=num && abs(candidates[i]-num)<mindiff)
30+ {
31+ mindiff = abs(candidates[i]-num);
32+ result = candidates[i];
33+ }
34+ else if(abs(candidates[i]-num)==mindiff)
35+ result = min(result, candidates[i]);
36+ }
37+ return to_string(result);
38+ }
39+ };
You can’t perform that action at this time.
0 commit comments