public class Palindrome {
public static void main(String args[]) {
String input = "Madam";
int number = 12321;
System.out.printf("Is %s a palindrome? : %b %n", input, isPalindrome(input));
System.out.printf("Is %s a palindrome? : %b %n", number, isPalindrome(number));
}
public static boolean isPalindrome(String input) {
if (input == null || input.isEmpty()) {
return true;
}
char[] array = input.toCharArray();
StringBuilder sb = new StringBuilder(input.length());
for (int i = input.length() - 1; i >= 0; i--) {
sb.append(array[i]);
}
String reverseOfString = sb.toString();
return input.equals(reverseOfString);
}
/*
* Java method to check if a number is palindrome or not
*/
public static boolean isPalindrome(int number) {
int palindrome = number; // copied number into variable
int reverse = 0;
while (palindrome != 0) {
int remainder = palindrome % 10;
reverse = reverse * 10 + remainder;
palindrome = palindrome / 10;
}
// if original and reverse of number is equal means
// number is palindrome in Java
if (number == reverse) {
return true;
}
return false;
}
/**
* * Java method to check if given String is Palindrome
* * @param text * @return true if text is palindrome, otherwise false
*/
public static boolean isPalindromString(String text) {
String reverse = reverse(text);
if (text.equals(reverse)) {
return true;
}
return false;
}
/**
* Java method to reverse String using recursion * @param input * @return reversed String of input
*/
public static String reverse(String input) {
if (input == null || input.isEmpty()) {
return input;
}
return input.charAt(input.length() - 1) + reverse(input.substring(0, input.length() - 1));
}
}
Comments
Post a Comment