Java – Check Palindrome Number
A number is said to be palindrome, if it is same as that of its value when reversed. For example 12521 is a palindrome and 12651 is not.
In this tutorial, we shall check if a number is palindrome in two ways. Firstly, by reversing the number and comparing it with the original value. Secondly, we shall traverse through each digit from start and end of the number, till its middle, checking if the digits are equal during each iteration.
Check Palindrome Number – Compare Original and Reverse
A number could be a palindrome if it equals the reverse of it.
In the following example, we shall reverse the given number in Java using StringBuilder, and compare it with its original value. If both are equal, then we can say that the given number is a palindrome.
PalindromeNumber.java
/**
* Java Program - Check if Number is Palindrome
*/
public class PalindromeNumber {
public static void main(String[] args) {
int n = 1236321;
//reverse the string
int rev = Integer.parseInt((new StringBuilder(n+"")).reverse().toString());
//check if n is palindrome
if(n==rev) {
System.out.println(n+" is Palindrome.");
} else {
System.out.println(n+" is not Palindrome.");
}
}
}
Output
1236321 is Palindrome.
Check if Number is Palindrome by Checking at Digit Level
Instead of reversing the number and checking for equality, we can check if the first and last digits are equal and progress to the middle of the number. If at any point, the digits are not equal, then it is not a palindrome.
Algorithm
We shall implement following algorithm in Java and write a program to check if given number is palindrome.
- Start.
- Take the number in n. We need to check if this is palindrome number or not.
- Take a boolean variable isPalindrome to store if the number is palindrome or not. Initialize it with
true
. - Initialize variable i with
0
. - Check if i is less than half the number of digits in n. If yes, go to step 6, else go to step 8.
- Check if digit in n at index i is equal to that of at
length-1-i
. If not set isPalindrome tofalse
and go to step 8. - Increment i. Go to step 5.
- Based on the value of isPalindrome, print the result.
- Stop.
PalindromeNumber.java
import java.lang.Math;
/**
* Java Program - Check if Number is Palindrome
*/
public class PalindromeNumber {
public static void main(String[] args) {
int n = 1236321;
//reverse the string
int length = (n+"").length();
boolean isPalindrome = true;
//check if ith digit is same from start and end
for(int i=0;i<length/2;i++) {
if( (n/(int)Math.pow(10, length-1-i))%10 != (n/(int)Math.pow(10, i))%10) {
isPalindrome = false;
break;
}
}
//check if str is palindrome
if(isPalindrome) {
System.out.println(n+" is Palindrome Number.");
} else {
System.out.println(n+" is not Palindrome Number.");
}
}
}
Output
1236321 is Palindrome Number.
Conclusion
In this Java Tutorial, we have written Java program using different techniques on how to check if given number is a palindrome or not.