Saturday, October 5, 2013

Q. Generate the next pallindrome number from a given 5 digit number

e.g
INPUT          36067

OUTUT        36163




METHOD

This  question  can  be  generalized  to  any  odd  number  digit  and  is  very  easy  and  mathematical  and  a  good  coding  question  too..

Well  I  am  not  able  to  find  any  other  method  for  this  question.

Take  the  number  in  an  array.....

int a[]=| 3 | 6 | 0 | 6 | 7 |

int  mid=a[2]=0

well  now  we  have  to  check  if  reverse  of  a[0..1]i.e  63  and  a[3...4]i.e  67,,

which  of  them  is  larger.. in  this  case  67

if  a[3...4]  is  larger,,  mid++;  And  our  example  belongs  to  this  case  so  0  becomes  1
else do  nothing...

now  just  reverse  the  a[0..1]  and  put  in  place  of  a[3...4]....  to  get  36163....



#include<stdio.h>


int main()

{

int n=36967;

int temp=n;

int mid=2;

int arr[5];

for(int k=4;k>=0;k--)

{

arr[k]=temp%10;

temp=temp/10;

}

//now compare  mid-1 and  mid+1  and  so  on......

for(int k=1;k<3;k++)

{

if(arr[mid-k]>arr[mid+k])

break;

else if(arr[mid+k]>arr[mid-k])

{

if(arr[mid]!=9)

arr[mid]++;

else

{arr[mid]=0;arr[mid-1]++;}

break;

}

else

continue;

}


     //  now  reverse  1st  part  and  2nd  part

     

     for(int k=1;k<3;k++)

     {

      arr[mid+k]=arr[mid-k];

     }


for(int k=0;k<5;k++)

printf("%d",arr[k]);

return 0;

}

 Hope  you  understood  everything..  And  please  tell  me  if  you  find  any  test  case  not  working
Any  suggestions  are  welcomed..


2 comments: