Palindrome Number
Palindrome number is a number which remains the same even after reversing the number, For example,:-, Let’s take a number 141 and reverse it then also it remains the same 141.
Steps to write the palindrome number
Step 1: Get the number from the user
Step 2: Store the number in the temporary variable
Step 3: Reverse the number
Step 4: Compare the reversed number with the temporary number
Step 5: If both the number matches then it palindrome number otherwise it is not.
Palindrome program in java
In this program, we are getting the number from the user
Import java.Util.Scanner;
Class Palindrome
{
Public static void main (String args{})
{
Int res, sum=0, temp, n;
Scanner s = new Scanner(System.in);
System.out.println(“ Enter the number: ”);
n = s.nextln();
temp = n;
while(n>0) // while loop to check whether the number is palindrome or not
{
res = n%10; // getting the remainder
sum = (sum *10)+res ;
n = n/10 ; // dividing by 10
}
If( temp == sum)
System.out.println(“ Number is palindrome”);
else
System.out.println (“ Number is not palindrome”);
}
}
Output
Enter the number: 141
Number is palindrome
Syntax
Compile -> javac Palindrome.java
Run -> java Palindrome
Code explanation:
Import java.Util.Scanner -> It’s a text scanner which can parse primitive types and strings using a regular expression.
Scanner s = new Scanner(System.in) -> It is used for receive input from keyboard.
n = s.nextln() -> This method are used for getting the integer value from the keyboard.
System.out.println (“……”) -> It is used for displaying the message on screen or console.
For this explanation, we are taking the input number as 14841
Step 1:
n = s.nextln();
The number we got from the user is stored in n
Step 2:
temp =n;
The number we got from the user is getting stored in a temporary allocation
Step 3:
while(n>0)
In the while loop, we checking whether the value of n is greater than 0. If it is greater than 0 it will enter the loop otherwise it will not enter the loop.
Step 4:
res = n%10;
Here the value of n is divided by 10 and its remainder is been stored in res
res = 141 % 10;
res = 1;
Step 5:
sum = (sum *10) + res ;
Here sum we had already initialized as 0
sum = (0*10) + 1;
sum = 1;
Step 6:
n = n /10;
n = 141 / 10;
n = 14;
After this again from step 3 it will get repeated step 6 till the value of n become less than or equal to 0
Step 7:
if (temp == sum)
In this step the initial value which was we stored in temp will be checked with the final value which is available in sum. If they are equal then it is palindrome number else not a palindrome number.