Wednesday, June 8, 2011

WAP to Find Nearest Palindrome of Given Number Efficiently

Given a number u need to find a closest palindrome of a number..
Example..
For Example 7957, the nearest palindrome is 7997
if i/p is 1999 then o/p is 2002 not 1991 (Special Case)

1st I thought About By Finding the solution using this algo

Algorithm
Find the Mid Number the from mid + 1 position copy the previous digits in the number in reverse order, i.e .... copy ( mid + 1 ..... N ) positions with ( mid ......1 )
but above case fail for 1999

#include

int nearPalin(int n){
int temp = n;
int count = 0;
while(temp>0){
temp /= 10;
count++;
}
if(count%2 == 0){
count = count/2;
while(count--)
n = n / 10;
temp = n;
printf("%d",n); //testing
while(n>0){
temp = temp*10 + n%10;
n = n/10;
}
return temp;
}
else{
count = count/2;
while(count--)
n = n / 10;
temp = n;
n = n/10;
printf("%d",n); //testing
while(n>0){
temp = temp*10 + n%10;
n = n/10;
}
return temp;
}
}

int main()
{
printf("%d",nearPalin(1999));//1234567890));
return 0;
}

Time Complexity O(N)
Space Complexity O(1)
Run Here http://ideone.com/8B7UO


So After Discussing From Some of The Friends we can solve with some efficient algorithm that will cover the all test cases.

Algorithm
Find The Mid Number & then store half number & append it into in reverse order to original.say it a.

2nd subtract 1 from mid of number & append this half number into reverse number to itself. it will show the number that is palindrome thats is less then given number.
say it b.

3rd add 1 to mid of number & then add reverse of this to itself it will represent the number thats palindrome greater then original number
say it c.

now we have to find which is near to original number so basically we have to find the minimum of 3 number.

Note: Need to Review. As This Algorithm Will Suffer With Integer Over Flow

#include
#include
using namespace std;
long long int abs(long long int a)
{
if (a>0)
return a;
return (-a);
}

int count(long long int a)
{
int count=0;
while (a>0)
{
a=a/10;
count++;
}

return count;

}
long long int reverse(long long int a)
{
long long int b=0;
while(a>0)
{
b=b*10+(a%10);
a=a/10;
}
return b;

}

long long int NearestPalindrom(long long int a,int size)
{
long long rev;

if(size%2==0)
rev=reverse(a);
else rev=reverse(a/10);

long long int num=a;

for (int i=0; i num=num*10;

num=num+rev;
return num;
}

int main()
{

long long int a;
cin>>a;
long long int num=a;

int sizea=count(a);
for(int i=0; i num=num/10;

long long int pa = NearestPalindrom(num,sizea);
long long int pb = NearestPalindrom(num-1,sizea);
long long int pc = NearestPalindrom(num+1,sizea);

int da,db,dc;
da=abs(pa-a);
db=abs(pb-a);
dc=abs(pc-a);
if (da cout< if (db cout< if (dc cout<
}

Time Complexity O(n)
Space Complexity O(1)
Run Here http://ideone.com/l1EY8

1 comment :

venkat said...

Finding the nearest among the pa,pb,pc can be improved