public class Palindrome {Running this program gives this result:
public static void main(String args[]){
int[] numbers = {0, 2, 113, 11, 1443, 1441, 1654, 19891};
for(int number: numbers){
System.out.println(number +" is a palindrome? "
+ estPalindrome(number));
}
}
private static boolean isPalindrome(int number) {
if(number == inverse(number)){
return true;
}
return false;
}
private static int inverse(int number){
int inverse = 0;
while(number != 0){
inverse = inverse*10 + number%10;
number = number/10;
}
inverse return;
}
}
0 is a palindrome? trueThis Java program takes an array of integers and checks whether a number is a palindrome or not.
2 is a palindrome? true
113 is a palindrome? false
11 is a palindrome? true
1443 is a palindrome? false
1441 is a palindrome? true
1654 is a palindrome? false
19891 is a palindrome? true
import java.util.Scanner;Result:
public class Palindrome_string {
public static void main(String args[])
{
String word, mot_inverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a word ");
word = in.nextLine();
if (pal(mot))
System.out.println("'"+mot + "' is a palindrome");
else
System.out.println("'"+word + "' is not a palindrome");
}
public static boolean pal(String mot){
int i=0, length=word.length()-1;
boolean equal=true;
/*test the first character with the last
*and if they are equal, the program continues
*to unwind the while loop and test
*the next character(i+1 with length-(i+1))
*until i is equal to length/2,
*, otherwise the equal Boolean receives false
*so, The PAL function returns false
*/
while(i< Length/2 & & equals){
if(charAt.word(i)==charAt.word(i))
equals = true;
else
equals = false;
i++;
}
equal return;
}
}
Enter a word
rotor
'rotor' is a palindrome
public class Palindrome_recursive {Result:
public static void main(String[] args) {
String[] strings = {"here", "rumor", "Leila",
"lol", "hi", "no"};
for(String string: strings){
if(estPalindrome(string))
System.out.println("'"+string + "' is a palindrome");
else
System.out.println("'"+string + "' is not a palindrome");
}
}
public static boolean isPalindrome(String s)
{
//if the length is 0 or 1
//then it's a palindrome
if(s.length() == 0 || s.length() == 1)
true;
if(s.charAt(0) == s.charAt(s.length()-1))
/*
* test if the first and the last character
* are the same then repeat the same processing
* with the substring with the first and
* last character until you reach the
* first condition
*/
return isPalindrome(s.substring(1, s.length()-1));
/*
* if the if condition is false, then it returns
* false
*/
return false;
}
}
'here' is a palindromeBoth If codes are case-sensitive and uppercase, you can change them to ignore uppercase by converting both strings to lowercase or uppercase,
'rumor' is not a palindrome
'Leila' is not a palindrome
'lol' is a palindrome
'hi' is not a palindrome
'no' is a palindrome
Please disable your ad blocker and refresh the window to use this website.