Write a program in Java to accept a number and check whether the number is a palindrome or not.
Answers
Answer:
class PalindromeExample{
public static void main(String args[]){
int r,sum=0,temp;
int n=454;//It is the number variable to be checked for palindrome
temp=n;
while(n>0){
r=n%10; //getting remainder
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");
}
}
Explanation:
Palindrome number in java: A palindrome number is a number that is same after reverse. For example 545, 151, 34543, 343, 171, 48984 are the palindrome numbers. It can also be a string like LOL, MADAM etc.
Palindrome number algorithm
Get the number to check for palindrome
Hold the number in temporary variable
Reverse the number
Compare the temporary number with reversed number
If both numbers are same, print "palindrome number"
Else print "not palindrome number"
Provided solution to the question asked to check whether the number entered by the user in Java is palindrome or not.
Introduction or Explanation:
Palindrome can be defined as a word, a number or sentence that reads the same backwards.
For Example:
• String:-
- RACECAR
- KANAK
- JALAJ
- LOL, etc.
• Number:-
- 32166123
- 45754
- 9822289
- 61316, etc.
Program:
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n, int r = 0;
System.out.println("Enter the number: ");
int num = in.nextInt();
while(n != 0)
{
int dig = n % 10;
n /= 10;
r = r * 10 + dig;
}
if (r == num)
System.out.println("A Palindrome number");
else
System.out.println("Not a Palindrome number");
}
}