spider68

V.IMP :Find the Closest Palindrome

Jul 4th, 2020
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. string nearestPalindromic(string n) {
  2.    if(n.length()==1) return to_string(stoi(n)-1); //Special case for single digit numbers
  3.    
  4.    int digits=n.length();
  5.    vector<long>candidates;
  6.    candidates.push_back(pow(10,digits-1)-1);//Case 1
  7.    candidates.push_back(pow(10,digits)+1);//Case 2
  8.  
  9.    int mid=(digits+1)/2;
  10.    long prefix=stol(n.substr(0,mid));
  11.    //Case 3
  12.    vector<long>v={prefix,prefix+1,prefix-1};
  13.    for(long i:v)
  14.    {
  15.        string postfix=to_string(i);
  16.        if(digits%2!=0) postfix.pop_back();//// If the total length is odd number, pop the middle number in postfix
  17.        reverse(postfix.begin(),postfix.end());
  18.        string c=to_string(i)+postfix;
  19.        candidates.push_back(stol(c));
  20.    }
  21.    long mindiff=LONG_MAX;long result;long num=stol(n);
  22.    for(int i=0;i<5;i++)
  23.    {
  24.        if(candidates[i]!=num&&abs(candidates[i]-num)<mindiff)//Candidate must not be the same number and abs diff is minm
  25.        {
  26.            mindiff=abs(candidates[i]-num);
  27.            result=candidates[i];
  28.        }
  29.        else if(abs(candidates[i]-num)==mindiff) result=min(result,candidates[i]);
  30.    }
  31.     return to_string(result);
  32. }
  33. };
Add Comment
Please, Sign In to add comment