Closest Palindrome Number (absolute difference Is min)

Given a number N. our task is to find the closest Palindrome number whose absolute difference with given number is minimum and absolute difference must be greater than 0.
Examples:

Input :  N = 121
Output : 131 or 111
Both having equal absolute difference
with the given number.

Input : N = 1234
Output : 1221

Asked In : Amazon

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Simple Solution is to find the largest palindrome number which is smaller to given number and also find the first palindrome number which is greater than Given number.we can find there Palindromic numbers by simply decreasing and increasing by one in given number until we find these palindromic numbers.

Below is implementation of above idea :

C++

 // C++ Program to find the closest Palindrome // number #include using namespace std;    // function check Palindrome bool isPalindrome(string n) {   for (int i = 0; i < n.size() / 2; i++)     if (n[i] != n[n.size() - 1 - i])       return false;   return true; }    // convert number into String string convertNumIntoString(int num) {      // base case:   if (num == 0)     return "0";      string Snum = "";   while (num > 0) {     Snum += (num % 10 - '0');     num /= 10;   }   return Snum; }    // function return closest Palindrome number int closestPlandrome(int num) {      // case1 : largest palindrome number   // which is smaller to given number   int RPNum = num - 1;      while (!isPalindrome(convertNumIntoString(abs(RPNum))))      RPNum--;        // Case 2 : smallest palindrome number   // which is greater than given number   int SPNum = num + 1;      while (!isPalindrome(convertNumIntoString(SPNum)))      SPNum++;        // check absolute difference   if (abs(num - RPNum) > abs(num - SPNum))     return SPNum;   else     return RPNum; }    // Driver program to test above function int main() {   int num = 121;   cout << closestPlandrome(num) << endl;   return 0; }

PHP

 0)  {     \$Snum .= (\$num % 10 - '0');     \$num =(int)(\$num / 10); } return \$Snum; }    // function return closest // Palindrome number function closestPlandrome(\$num) {    // case1 : largest palindrome number // which is smaller to given number \$RPNum = \$num - 1;    while (!isPalindrome(convertNumIntoString(abs(\$RPNum))))      \$RPNum--;     // Case 2 : smallest palindrome number // which is greater than given number \$SPNum = \$num + 1;    while (!isPalindrome(convertNumIntoString(\$SPNum)))      \$SPNum++;     // check absolute difference if (abs(\$num - \$RPNum) > abs(\$num - \$SPNum))     return \$SPNum; else     return \$RPNum; }        // Driver code     \$num = 121;     echo closestPlandrome(\$num)."\n";    // This code is contributed by mits ?>

Output:

111

An efficient solution is to consider following cases.

Case 1: If a number contains all 9’s then we get next closest Palindrome by simply adding 2 in it. num = 999 : output : num + 2 = 1001.

Case 2:
Case 2 a :One possible way to getting closest palindromic by Copy first half and add mirror image at the end if it. Left half : For example, left side of “123 456” is “123” and left half of “12345” is “1 2”. To convert to palindrome, we can either take the mirror of its left half or take mirror of its right half. However, if we take the mirror of the right half, then the palindrome so formed is not guaranteed to be the closest palindrome. So, we must take the mirror of left side and copy it to right side.

Let's number : 123456
After copy and append reverse of it at the end number looks like:
we get palindrome 123321

case 2 b and 2c: Two more possible ways of getting the closest palindromic number by decrementing and incrementing middle digit by one on palindrome.

Below is the implementation of above idea :

C++

 // CPP program to find the closest Palindrome number #include using namespace std;    #define CToI(x) (x - '0') #define IToC(x) (x + '0')    // function check Palindrome bool isPalindrome(string n) {     for (int i = 0; i < n.size() / 2; i++)         if (n[i] != n[n.size() - 1 - i])             return false;     return true; }    // check all 9's bool checkAll9(string num) {     for (int i = 0; i < num.size(); i++)         if (num[i] != '9')             return false;     return true; }    // Add carry to the number of given size string carryOperaion(string num, int carry, int size) {     if (carry == -1)     {         int i = size - 1;         while (i >= 0 && num[i] == '0')             num[i--] = '9';         if (i >= 0)             num[i] = IToC(CToI(num[i]) - 1);     }     else     {         for (int i = size - 1; i >= 0; i--)         {             int digit = CToI(num[i]);             num[i] = IToC((digit + carry) % 10);             carry = (digit + carry) / 10;         }     }     return num; }    // function return the closest number // to given number string MIN(long long int num,            long long int num1,            long long int num2,            long long int num3) {        long long int Diff1 = abs(num - num1);     long long int Diff2 = abs(num - num2);     long long int Diff3 = abs(num3 - num);        if (Diff1 < Diff2 && Diff1 < Diff3 &&         num1 != num)         return to_string(num1);     else if (Diff3 < Diff2 && (Diff1 == 0 ||              Diff3 < Diff1))         return to_string(num3);     else         return to_string(num2); }    // function return closest Palindrome number string closestPlandrome(string num) {        // base case     if (num.size() == 1)         return (to_string(stoi(num) - 1));        // case 2:     // If a number contains all 9's     if (checkAll9(num))     {         string str = "1";         return str.append(num.size() - 1, '0') + "1";     }        int size_ = num.size();        // case 1 a:     // copy first half and reverse it and append it     // at the end of first half     string FH = num.substr(0, size_ / 2);     string odd;        // odd length     if (size_ % 2 != 0)         odd = num[size_ / 2];        // reverse     string SH = FH;     reverse(SH.begin(), SH.end());        // store three nearest Palindrome numbers     string RPNUM = "", EPNUM = "", LPNUM = "";     string tempFH = "";     string tempSH = "";        if (size_ % 2 != 0)     {         EPNUM = FH + odd + SH;         if (odd == "0")         {             tempFH = carryOperaion(FH, -1, FH.size());             tempSH = tempFH;             reverse(tempSH.begin(), tempSH.end());             RPNUM = tempFH + "9" + tempSH;         }         else             RPNUM = FH + to_string(stoi(odd) - 1) + SH;            // To handle carry         if (odd == "9")         {             tempFH = carryOperaion(FH, 1, FH.size());             tempSH = tempFH;             reverse(tempSH.begin(), tempSH.end());             LPNUM = tempFH + "0" + tempSH;         }         else             LPNUM = FH + to_string(stoi(odd) + 1) + SH;     }        // for even case     else     {         int n = FH.size();         tempFH = FH;         EPNUM = FH + SH;         if (FH[n - 1] == '0')             tempFH = carryOperaion(FH, -1, n);         else             tempFH[n - 1] = IToC(CToI(FH[n - 1]) - 1);            tempSH = tempFH;         reverse(tempSH.begin(), tempSH.end());         RPNUM = tempFH + tempSH;            tempFH = FH;         if (FH[n - 1] == '9')             tempFH = carryOperaion(FH, 1, n);         else             tempFH[n - 1] = IToC(CToI(tempFH[n - 1]) + 1);            tempSH = tempFH;         reverse(tempSH.begin(), tempSH.end());         LPNUM = tempFH + tempSH;     }        // return the closest palindrome numbers     return MIN(stoll(num), stoll(EPNUM), stoll(RPNUM),                                          stoll(LPNUM)); }    // Driver program to test above function int main() {     string num = "123456";     cout << closestPlandrome(num) << endl;     return 0; }

Output:

123321

Time complexity : O(d) ( d is the number of digit in given number )

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : Mithun Kumar, mahendera

Article Tags :
Practice Tags :

5

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.