Tuesday, 15 December 2015

Program to find the Next Palindrome Number

JAVA Program to find Next PALINDROME NUMBER

import java.*;
public class NextPalindromNumber {
public static void main(String[] args) {
//String  num = "123450";
String num=args[0];
int len=num.length();
if(len%2 == 1)
{       int m=len/2;
String substr1 =num.substring(0, m);
//System.out.println("substring1 : " + substr1);
String substr2 = num.substring(m+1);
//System.out.println("substring2 : "+ substr2);
String revsubstr1 = new StringBuilder(substr1).reverse().toString();
if(revsubstr1.equals(substr2))
{
                           System.out.println("Number is already a palindrome");
}
else
{      int num1=Integer.parseInt(revsubstr1);
int num2=Integer.parseInt(substr2);
if(num2 > num1)
{
char c = num.charAt(m);
//System.out.println("char at middle :" + c);
if(Character.getNumericValue(c)==9)
{
String res0=num.substring(0,m);
int value = Integer.parseInt(res0);
value++;
res0=value+"";
String res2=new StringBuilder(res0).reverse().toString();

String res1=res0 +"0" + res2;
System.out.println(res1);
}
else
{
int x = Character.getNumericValue(c)+1;
//System.out.println(x);
String res0=num.substring(0,m) ;
String res2=new StringBuilder(res0).reverse().toString();
String res1=res0 + x+ res2;
System.out.println(res1);
}
}
else
{
String res0=num.substring(0,m);
String res2=new StringBuilder(res0).reverse().toString();
String res1=num.substring(0, m+1)+res2;
System.out.println(res1);
}
}
}
else
{ int m=len/2;
String substr1 =num.substring(0, m);
String substr2 = num.substring(m);
String revsubstr1 = new StringBuilder(substr1).reverse().toString();
int num1=Integer.parseInt(revsubstr1);
int num2=Integer.parseInt(substr2);
if(num2>num1)
{
int value=Integer.parseInt(substr1);
value++;
String res0=value+"";
String res2=new StringBuilder(res0).reverse().toString();
String res1=res0+res2;
System.out.println(res1);
}
else
{
String res2=new StringBuilder(substr1).reverse().toString();
String res1=substr1+res2;
System.out.println(res1);
}
}
}

}

No comments:

Post a Comment