Thursday, June 2, 2011

WAP Find The Next Largest Palindrome of Given Number Need not to b Palindrome

PS: Don't Get Confused it With Finding Next Palindrome Post

Algorith

1. counts the tottal no of digits in given number & place value of MSB
placevalue will help us to find half no from MSB
2. Get the num till half of the number of digit of given num.
3. Add 1 in to it.
4. Reverse the num obtained in step 2.
5. Append the numbers obtained in 2 and 3.

#include


int nextPalindromInt(int inPalindromeInt)
{
int numOfDigit=0, placeValue=1;
int num=inPalindromeInt, halfNum=0, i;
/*Get Total num of digit and place value of most significant digit*/
while(num)
{
numOfDigit++;
num=num/10;
placeValue = placeValue*10;
}
i=(numOfDigit>>1)+((numOfDigit%2));

num=inPalindromeInt;
placeValue=placeValue/10;

//printf( " %d %d ",i,placeValue);

/*Get the num till half of the number of digit*/
while(i)
{
halfNum = halfNum*10 + num/placeValue;
num=num%placeValue;
placeValue = placeValue/10;
i--;
}
/*Add one in halfnum, get next palindrome by appending
halfNum in to halfNum in reverse manner*/
halfNum=halfNum+1;
num=halfNum;

/*if(numOfDigit%2) Used as optimization Step can be omitted
{
num=halfNum/10;
}*/

while(num)
{
halfNum=halfNum*10 + num%10;
num=num/10;
}
return halfNum;
}

int main()
{

printf("%d",nextPalindromInt(123456));
return 0;
}



TC O(K) k length of number
SC O(1)
Run Here https://ideone.com/FpgEj

1 comment :

Shan said...

This program will not generate correct output for 808. It generates 8118 but actual answer is 818. check it. My email: santanu.code@gmail.com