Showing posts with label Integer Palindrome using Java. Show all posts
Showing posts with label Integer Palindrome using Java. Show all posts

Saturday, August 18, 2012

Palindrome in Java for Integers and Strings


public class JavaPalindrome {

public static void main(String arg[]){
int num=121;
String str="teet teet";
System.out.println("Given Number"+num+"is Palindrome:"+intPalindrome(num));
System.out.println("Given String"+str+"is Palindrome:"+stringPalindrome(str));
System.out.println("String reverse using toChar Array");
System.out.println("Given String"+str+"is  Palindrome:"+stringCharArrayPalindrome(str));
}

private static boolean stringCharArrayPalindrome(String str) {
String rev="";
char arr[]=str.toCharArray();
for(int i=arr.length-1;i>=0;i--)
rev=rev+arr[i];
if(str.equalsIgnoreCase(rev))
return true;
else
return false;

}

private static boolean stringPalindrome(String st) {
String str1[]=st.split("");
   String revstr="";
   for(int i=str1.length-1;i>=0;i--){
       revstr+=str1[i];
   }
   if(st.equalsIgnoreCase(revstr))
    return true;
   else
    return false;
   }

// Checking Number Palindrome or not
private static boolean intPalindrome(int num) {
int n = num;
        int rev = 0;
        for (int i = 0; i <= num; i++)
        {
            int r = num % 10;
            num = num / 10;
            rev = rev * 10 + r;
            i = 0;
         }
       
        if (n == rev) {
            return true;
        } else {
            return false;
        }
}/** Number palindrome */

}