Skip to content

Commit

Permalink
Create 564. Find the Closest Palindrome (#566)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Aug 24, 2024
2 parents 85af9b4 + f6359ab commit faf2019
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions 564. Find the Closest Palindrome
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
public:
string nearestPalindromic(string n) {
if(n.length()==1)
return to_string(stoi(n)-1);

int d = n.length();
vector<long> candidates;
candidates.push_back(pow(10,d-1)-1);
candidates.push_back(pow(10,d)+1);

int mid = (d+1)/2;
long prefix = stol(n.substr(0,mid));
vector<long> v = {prefix,prefix+1, prefix-1};
for(long i : v)
{
string postfix = to_string(i);
if(d%2!=0)
postfix.pop_back();
reverse(postfix.begin(), postfix.end());
string c = to_string(i)+postfix;
candidates.push_back(stol(c));
}
long mindiff = LONG_MAX;
long result;
long num = stol(n);
for(int i=0;i<5;i++)
{
if(candidates[i]!=num && abs(candidates[i]-num)<mindiff)
{
mindiff = abs(candidates[i]-num);
result = candidates[i];
}
else if(abs(candidates[i]-num)==mindiff)
result = min(result, candidates[i]);
}
return to_string(result);
}
};

0 comments on commit faf2019

Please sign in to comment.