What is palindrome?
A number
or a phrase that is same when you read from backward or forward. It ignores
spaces, capital letters and punctuation.
Eg:12321, level.
Logic:
- · Read the input from the user.
- · First, reverse the digits of the given number.
- · Check the original number and reverse number. If both are equal,then the number is palindrome.
- · Otherwise, it is not a palindrome number.
Program implementation:
To implement the concept, follow the steps given below.
- · First, include the java package java.util.Scanner.
- · Create a class LetusCheckPalindrome with main() function.
- · An object is created for Scanner. Using the object,call the function “nextInt()” to get the number.
- · Create two integers originalNo,revNo and assign to 0.
- · While the n is not equal to 0, repeat the loop.
- · Reverse the digit.
- · Check the originalNo and revNo
- · If both numbers are equal then the given number is a palindrome.
- · Otherwise, it is not a palindrome. Print the message.
Program:
//Java Program to check the number is palindrome or not
import java.util.Scanner;
public class LetusCheckPalindrome {
public static void
main(String[] args) {
Scanner sObj =
new Scanner(System.in);
System.out.print("Enter
the number");
int n =
sObj.nextInt();
int originalNo
= n;
int revNo = 0;
while (n!= 0) {
int digit
= n % 10;
revNo =
revNo * 10 + digit;
n /= 10;
}
if (originalNo == revNo) {
System.out.println("The given number is a palindrome.");
} else {
System.out.println("The given number is not a palindrome.");
}
}
}
Compile and execute the program.
Output:
Here, is the output.
C:\raji\blog>javac LetusCheckPalindrome.java
C:\raji\blog>java LetusCheckPalindrome
Enter the number678
The given number is not a palindrome.
C:\raji\blog>java LetusCheckPalindrome
Enter the number12321
The given number is a palindrome.
That’s all. The java program to check the given number is
palindrome or not is implemented successfully.
No comments:
Post a Comment