In this post we’ll see how to write a Java program to check whether a given number is palindrome or not.
A number is said to be a palindrome if it remains same when reversed as example 1221, 1001.
Java program – Given number is palindrome or not
In order to find if a given number is palindrome or not in Java you can reverse the number and then compare it with the original number. If both are same then the passed number is a palindrome.
In order to reverse the passed number you will have to do modulo division with 10 (till the number remains greater than 0) to get the last digit (remainder) of the number and then form the new number.
public class PalindromeNumber { public static void main(String[] args) { checkPalindrome(1221); checkPalindrome(201); checkPalindrome(1001); } private static void checkPalindrome(int number){ int reverseNum = 0; int remainder; int originalNum = number; while (number > 0) { remainder = number % 10; reverseNum = (reverseNum * 10) + remainder; number = number / 10; } if(reverseNum == originalNum){ System.out.println(originalNum + " is a Palindrome"); }else{ System.out.println(originalNum + " is not a Palindrome"); } } }Output
1221 is a Palindrome 201 is not a Palindrome 1001 is a Palindrome
That's all for the topic Check Given Number Palindrome or Not in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like
- Java Program to Check Given String Palindrome or Not
- Java Program to Check Whether Number Prime or Not
- Java Program to Check if Armstrong Number
- Java Programs For Displaying Patterns
- Java Pass by Value or Pass by Reference
- Java HashSet With Examples
- Fail-fast And Fail-safe Iterators in Java
- Counters in Hadoop MapReduce
- Spring Bean Definition Inheritance
No comments:
Post a Comment