June 22, 2022

Check Given Number Palindrome or Not in Java

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) {

  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");
      System.out.println(originalNum + " is not a Palindrome");
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

No comments:

Post a Comment