Skip to content

Commit faf2019

Browse files
authored
Create 564. Find the Closest Palindrome (#566)
2 parents 85af9b4 + f6359ab commit faf2019

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

564. Find the Closest Palindrome

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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+
};

0 commit comments

Comments
 (0)