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 userint n1=n; //equating original number to n1int s=0; //initializing sum to 0while(n>0){ //reversing numberint d=n%10;s=s*10+d;n=n/10;}if(n1==s) //checking for palindromeSystem.out.println("Palindrome Number");elseSystem.out.println("Not Palindrome");}}
Enter the input below