I was asked by a friend to explain a palindrome program in java and I wanted to make it work for both integers and strings. In addition, wanted to make it short and understandable. Checking if a string is a palindrome or not is simple when compared to an integer palindrome. With a string, we can compare the first character with last character, second character with last but one character and so on. In java, we can convert an integer to string using Integer.toString().
In the below we have two methods, with the same name but different types of parameters passed. If an integer is passed parameter, it is converted to string and the same is passed to the method with string argument. Here it is checked if it is a palindrome by checking if it is like a mirror image, with mirror in the middle of the string. If yes, 1 is returned else, -1 is returned. The same value returned by string method is again returned by the integer method.
In the below we have two methods, with the same name but different types of parameters passed. If an integer is passed parameter, it is converted to string and the same is passed to the method with string argument. Here it is checked if it is a palindrome by checking if it is like a mirror image, with mirror in the middle of the string. If yes, 1 is returned else, -1 is returned. The same value returned by string method is again returned by the integer method.
/**
* Created by Naveen Kumar on 9/30/2015.
*/
public class PalindromeDemo {
public static void main(String args[]){
PalindromeDemo pd = new PalindromeDemo();
System.out.println((pd.palindromeCheck(343)==1)?"Palindrome":"Not Palindrome");
System.out.println((pd.palindromeCheck(3432)==1)?"Palindrome":"Not Palindrome");
System.out.println((pd.palindromeCheck("madam")==1)?"Palindrome":"Not Palindrome");
System.out.println((pd.palindromeCheck("abcd")==1)?"Palindrome":"Not Palindrome");
}
public int palindromeCheck(int n){
return (new PalindromeDemo()).palindromeCheck(Integer.toString(n));
}
public int palindromeCheck(String str){
for(int i=0;i<(str.length())/2;i++){
if(str.charAt(i)!=str.charAt(str.length()-i-1))
return -1;
}
return 1;
}
}
* Created by Naveen Kumar on 9/30/2015.
*/
public class PalindromeDemo {
public static void main(String args[]){
PalindromeDemo pd = new PalindromeDemo();
System.out.println((pd.palindromeCheck(343)==1)?"Palindrome":"Not Palindrome");
System.out.println((pd.palindromeCheck(3432)==1)?"Palindrome":"Not Palindrome");
System.out.println((pd.palindromeCheck("madam")==1)?"Palindrome":"Not Palindrome");
System.out.println((pd.palindromeCheck("abcd")==1)?"Palindrome":"Not Palindrome");
}
public int palindromeCheck(int n){
return (new PalindromeDemo()).palindromeCheck(Integer.toString(n));
}
public int palindromeCheck(String str){
for(int i=0;i<(str.length())/2;i++){
if(str.charAt(i)!=str.charAt(str.length()-i-1))
return -1;
}
return 1;
}
}
Any comments or updates are welcome :)
Happy Coding.
No comments:
Post a Comment