-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 564. Find the Closest Palindrome
- Loading branch information
1 parent
85af9b4
commit f6359ab
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
}; |