Java Program For Checking A Number Palindrome
Just like palindrome string we discussed in our previous article and wrote a program for checking the palindrome string,same rule applies for the palindrome number.A number is palindrome if it remains same after reversing sequence of its digits.For example- suppose we have a number 121, if we reverse it then we will get a the same number 121, so the given number is a palindrome.Similarly 1221,525,52525 etc all are palindrome numbers.
Now after knowing the definition of a palindrome number we can write our code easily.So here is the algorithm we will appy for writing the program-
Now after knowing the definition of a palindrome number we can write our code easily.So here is the algorithm we will appy for writing the program-
- Get the user input,the number which we are going to check for palindrome, for this purpose we will use Scanner class in java
- Store that number in a int variable
- Reverse the scanned number and store it in an another int variable
- Compare the values of both int variables and print the result accordingly
package in.blogger.tutorialsinn import java.util.Scanner; public class NumberPalindrome { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number you want to check"); int number = sc.nextInt(); int temp = number; // calculating length of number int length = (int) (Math.log10(temp) + 1); // calculating reverse number int rev = 0; for (int i = 1; i <= length; i++) { int rem = temp % 10; temp = temp / 10; rev = (rev * 10) + rem; } System.out.println("reverse number is " + rev); // checking for equality and printing result if (number == rev) { System.out.println("Given number is a palindrome"); } else { System.out.println("Given number is not a palindrome"); } } }Output- Enter the number you want to check 121 reverse number is 121 Given number is a palindrome I hope that you now understood the flow of whole program and can use your own logic for writing another palindrome program.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment