The Below program will tell you the given number is palindrome or not. In generally most of the interviewers are asking this question during interview process and candidates struggling to answer this question. Please practice the below program, this will help you. I hope.
package testing;
import java.util.Scanner;
/**
* Please find the Java program to check if given number is palindrome or not.
* If number and its reverse is equal then this is called palindrome
* This program can also be used to reverse a number in Java
*/
public class Palindromeprogram {
public static void main(String args[]){
System.out.println("Please Enter a number : ");
int palindrome = new Scanner(System.in).nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number : " + palindrome + " is a palindrome");
}else{
System.out.println("Number : " + palindrome + " is not a palindrome");
}
}
/*
* Here Java method to check if given 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 (number == reverse) {
return true;
}
return false;
}
}
Output:
Please Enter a number :
2345
Number : 2345 is not a palindrome
Please Enter a number :
21012
Number : 21012 is a palindrome
import java.util.Scanner;
/**
* Please find the Java program to check if given number is palindrome or not.
* If number and its reverse is equal then this is called palindrome
* This program can also be used to reverse a number in Java
*/
public class Palindromeprogram {
public static void main(String args[]){
System.out.println("Please Enter a number : ");
int palindrome = new Scanner(System.in).nextInt();
if(isPalindrome(palindrome)){
System.out.println("Number : " + palindrome + " is a palindrome");
}else{
System.out.println("Number : " + palindrome + " is not a palindrome");
}
}
/*
* Here Java method to check if given 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 (number == reverse) {
return true;
}
return false;
}
}
Output:
Please Enter a number :
2345
Number : 2345 is not a palindrome
Please Enter a number :
21012
Number : 21012 is a palindrome