Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Nearest Palindrome.cpp #251

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions Nearest Palindrome.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// C++ Program to find the closest Palindrome
// number
#include <bits/stdc++.h>
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 closestPalindrome(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 << closestPalindrome(num) << endl;
return 0;
}