When palindrome numbers are reversed, they result in the same number.
For example:
121
454
12121
16461 etc
Accept a number by using the Scanner class from a user (n
).
Equate one variable, suppose n1
to original number n
and sum to 0
.
If the original number is greater than 0
, we perform palindrome logic.
Extract the last digits using the modulus symbol(%
).
Then, reverse the number using the last digits and store it in the sum variable.
Finally, remove the last digit using the division symbol ( /
).
Check for the palindrome, if the original number is equal to the sum, then the given number is either a palindrome or it is not a palindrome.
The code below is used a check if a given number is a palindrome.
import java.util.*; class Palin { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); //accepting number from user int n1=n; //equating original number to n1 int s=0; //initializing sum to 0 while(n>0) { //reversing number int d=n%10; s=s*10+d; n=n/10; } if(n1==s) //checking for palindrome System.out.println("Palindrome Number"); else System.out.println("Not Palindrome"); } }
Enter the input below
RELATED TAGS
CONTRIBUTOR
View all Courses