Related Tags

palindrome
java
reverse
communitycreator

How to check palindrome numbers in Java

Nalla Yasasvi

When palindrome numbers are reversed, they result in the same number.

For example:
121
454
12121
16461 etc

Algorithm

1. Accept a number by using the Scanner class from a user (n).

2. Equate one variable, suppose n1 to original number n and sum to 0.

3. If the original number is greater than 0, we perform palindrome logic.

4. Extract the last digits using the modulus symbol(%).

5. Then, reverse the number using the last digits and store it in the sum variable.

6. Finally, remove the last digit using the division symbol ( /).

7. 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.

Code

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

palindrome
java
reverse
communitycreator

CONTRIBUTOR

Nalla Yasasvi
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time