Java Program to check the given number is PALINDROME or NOT.
Objective
Write a Java program to check if an integer is a palindrome (reads the same forwards and backwards).
Algorithm / Approach
- Read an integer
nfrom the user. - Store the original value of
nin a variableorig. - Initialize an integer
revto 0. - Start a
whileloop as long asn > 0. - Extract the last digit using
t = n % 10. - Append it to
revusingrev = (rev * 10) + t. - Remove the last digit from
nusingn = n / 10. - Compare
origwithrev; if they match, it is a palindrome.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a Num: ");
int n = s.nextInt();
int orig= n;
int rev =0;
while(n>0) {
int t = n%10;
rev = 10*rev+t;
n = n/10;
}
if(orig==rev) {
System.out.print("Palindrome");
}
else {
System.out.print("NOT Palindrome");
}
}
}
Expected Output
Enter a Num: 12321 Palindrome
Explanation of the Program
- A palindrome reads the same in both directions (e.g., 12321).
- To reverse the number, the program extracts the last digit using modulo 10 (
% 10) and appends it to the reversed number. - Multiplying the current reversed number by 10 shifts its digits to the left, making room for the newly extracted digit.
- Because the original
nis destroyed during the loop, a copy (orig) is saved at the beginning for the final comparison.
Complexity
Time Complexity
O(log10(n)) - Iterates exactly as many times as there are digits.
Space Complexity
O(1)
Common Mistakes
- Comparing
revagainstninstead oforigat the end. At the end of the loop,nis always 0. - Not saving the original value before the loop starts.