Find the Closest Palindrome in C++


Suppose we have a number n, we have to get the closest number that is palindrome. So the palindrome could be less than or greater than the number whose absolute difference is smaller. So if the number is like 145, then the result will be 141.

To solve this, we will follow these steps −

  • sn := size of n
  • if sn is same as 1, then −
    • decrease n[0] by 1 and return a string of 1s of size n[0]
  • half_sn := (sn + 1) / 2
  • half_val := stol(substring of n from index 0 to half_sn
  • Define an array candidates = {10^(sn) – 1, 10^(sn - 1) - 1, 10^(sn - 1) + 1, 10^(sn)+1
  • Define an array fmdc = { half_val, half_val - 1, half_val + 1 }
  • for each value c in fmds
    • rev := convert c to string
    • if sn mod 2 is non-zero, then −
      • delete last element from rev
    • reverse the array rev
    • insert c at the end of candidates
  • sort the array candidates
  • val := n as integer
  • for each candidate in candidates −
    • if candidate is same as val, then −
      • Ignore following part, skip to the next iteration
    • diff := abs|candidate – val|
    • if diff < min_diff, then −
      • min_diff := diff
      • ans := convert candidate to string
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string nearestPalindromic(string n) {
      int sn = n.size();
      if(sn == 1){
      return string(1, --n[0]);
   }
   int half_sn = (sn+1)/2;
   long half_val = stol(n.substr(0, half_sn));
   vector<long> candidates = {pow(10, sn)-1, pow(10, sn-1)-1, pow(10, sn-1)+1, pow(10, sn)+1};
   vector <long> fmdc = {half_val, half_val-1,half_val+1};
   for(long c:fmdc){
      string rev = to_string(c);
      if(sn%2)rev.pop_back();
      reverse(rev.begin(),rev.end());
      candidates.push_back(stol(to_string(c) + rev));
   }
   sort(candidates.begin(), candidates.end());
   string ans;
   long val = stol(n), min_diff = INT_MAX;
   for(long candidate : candidates){
      if(candidate == val)continue;
      long diff = labs(candidate - val);
      if(diff < min_diff){
         min_diff = diff;
         ans = to_string(candidate);
         }
      }
      return ans;
   }
};
main(){
   Solution ob;
   cout << (ob.nearestPalindromic("145"));
}

Input

“145”

Output

141

Updated on: 01-Jun-2020

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements