Interview Questions

177. Find next palindrome of a number.......

Microsoft Interview Questions and Answers


(Continued from previous question...)

177. Find next palindrome of a number.......

Question:
Find next palindrome of a number. eg 125 next palindrome is 131


maybe an answer:


//find next palindrome of a number. eg 125 next palindrome is 131
import java.util.*;
class NextPalindome
{
public static void main(String args[])
{
System.out.println("Enter a number ");
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
int y=nextP(x);
System.out.println("Next Palindrome of "+x+" is "+y);
}
static int nextP(int x)
{
if(x<0)
return -1*nextP(-x);
else if(x<10)
return x;
ArrayList<Integer> a=new ArrayList<Integer>();
boolean inc=false;
while(x>0)
{
a.add(x%10);
x=x/10;
}
int l=0,u=a.size()-1;
while(l<u)
{
if(a.get(u)>a.get(l))
inc=true;
else if(a.get(u)<a.get(l))
inc=false;
a.set(l,a.get(u));
l++;
u--;
}
int b=(a.size()-1)/2,f=a.size()/2;
while(!inc)
{
if(b<0)
return augment(a.size());
int s=a.get(f)+1;
if(s<10)
{
a.set(b,s);
a.set(f,s);
inc=true;
}
else
{
a.set(b,0);
a.set(f,0);
b--;
f++;
}
}
return makeInt(a);
}
static int makeInt(ArrayList<Integer> a)
{
int x=0;
for(int i=a.size()-1;i>=0;i--)
x=x*10+a.get(i);
return x;
}
static int augment(int n)
{
int x=1;
for(int i=0;i<n;i++)
x=x*10;
return x+1;
}
}

(Continued on next question...)

Other Interview Questions