A number is said to be palindrome if it reads both forward and backwards same.
Example-
175571
454
A program for palindrome number can be made by simply extracting digits of the number in reverse order and adding them with their place value and then checking is it same as the original number or not.
To extract a digit in revers order and adding with place value we simply follow the below code.
while(n>0)
{
int d=n%10;
rev=(rev*10)+d;
n=n/10;
}
To explain this let us take an example 657
Then
For first iteration = n=657
d=657%10=7
rev=(0*10)+7=7
For second iteration = n=65
d=65%10=5
rev=(7*10)+5=75
For third iteration = n=6
d=6%10=6
rev=(75*10)+6=756
Hence, we get the reverse of the number.
ALGORITHM-
STEP 1: Start STEP 2: print "enter a number" STEP 3: taking input of integer in num STEP 4: initializing integer rev =0 STEP 5: intializing integer n=num STEP 6: repeat STEP 6 to STEP 8 until n>0 STEP 7: int d=n%10 STEP 8: rev=(rev*10)+d STEP 9: n=n/10 STEP 10:if(rev==num) then goto STEP 11 else goto STEP 12 STEP 11: print num+" is a palindrome number" STEP 12: print num+" is not a palindrome number" STEP 13: end |
JAVA CODE -
import java.util.*;
Output-
public class palin
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a number");
int num=sc.nextInt();
int rev=0;
int n=num;
while(n>0)
{
int d=n%10;
rev=(rev*10)+d;
n=n/10;
}
if(rev==num)
System.out.println(num+"is a palindrome number");
else
System.out.println(num+"is not a palindrome number");
}
}
enter a number
You can checkout similar java codes
454
454 is a palindrome number
If you have any query ask in comments
Comments
Post a Comment