# Find the Closest Palindrome in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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 by 1 and return a string of 1s of size n
• 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);
}
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