Java Program to Check Palindrome Number

class PalindromeNumber

{

  public static void main(String[] args)

  {   

    int num = 755, reversedNum = 0, remainder;

   

    // store the number to originalNum

    int originalNum = num;

   

    // get the reverse of originalNum

    // store it in variable

    while (num != 0) {

      remainder = num % 10;

      reversedNum = reversedNum * 10 + remainder;

      num /= 10;

    }

   

    // check if reversedNum and originalNum are equal

    if (originalNum == reversedNum) {

      System.out.println(originalNum + " is Palindrome.");

    }

    else {

      System.out.println(originalNum + " is not Palindrome.");

    }

  }

}


Output :

755 is not a palindrome

Explanation :


1. Variable Initialization:
  • num is initialized to the number 755, which is the number we want to check for palindromicity.
  • reversedNum is initialized to 0, which will store the reverse of num.
  • remainder is declared to store the remainder when num is divided by 10.
  • originalNum is used to store the original value of num because we need it for comparison later.
2. Reverse the Number: The program enters a while loop, which continues as long as num is not equal to 0. Inside the loop:
  • remainder is calculated by taking the remainder when num is divided by 10. This gives the last digit of num.
  • reversedNum is updated by multiplying its current value by 10 and adding the remainder. This effectively reverses the digits of num.
  • num is updated by integer division (num /= 10), removing the last digit.
3. Check for Palindrome: 
After the loop, num becomes 0 because all its digits have been processed. Now, reversedNum holds the reverse of the original number.
4. Comparison: The program compares the originalNum (the original number) with reversedNum (the reverse of the original number).
  • If they are equal, it means the original number is a palindrome, so it prints a message saying that the number is a palindrome.
  • If they are not equal, it means the original number is not a palindrome, so it prints a message saying that the number is not a palindrome.
In this specific example, since num was initially set to 755, after reversing its digits, reversedNum becomes 557. Therefore, the program will output:

Comments

Popular posts from this blog

Installing MySQL and MySQL Workbench

Constructor