Java Practice Program: given number is a palindrome

Write a Java program that checks if a given number is a palindrome.

This Java program checks if a given number is a palindrome. A palindrome number is a number that remains the same when its digits are reversed.

class Main {
    public static void main(String[] args) {
        int userNo = 40;  // You can change this to any number to check
        int originalNo = userNo;  // Store the original number
        int revNo = 0;

        // Reverse the digits of userNo
        while (userNo != 0) {
            int digit = userNo % 10;  // Get the last digit
            revNo = revNo * 10 + digit;  // Build the reversed number
            userNo /= 10;  // Remove the last digit
        }

        // Compare the original number with the reversed number
        if (originalNo == revNo) {
            System.out.print("palindrome");
        } else {
            System.out.print("not palindrome");
        }
    }
}

Output:

not palindrome

Variable Initialization:
userNo = 40: The number to check if it is a palindrome.
originalNo = userNo: Stores the original number so it can be compared with the reversed number.
revNo = 0: A variable to store the reversed version of userNo.

Reversing the Number:
The while loop runs as long as userNo is not equal to 0.
userNo % 10 extracts the last digit of the number.
revNo = revNo * 10 + digit shifts the digits of revNo left (by multiplying by 10) and adds the extracted digit to form the reversed number.
userNo /= 10 removes the last digit from userNo.

Comparison and Output:
After reversing the digits of userNo, the program compares the reversed number (revNo) with the original number (originalNo).
If they are the same, the number is a palindrome, and it prints “palindrome”.
If they are different, it prints “not palindrome”.

Example Outputs
For userNo = 40:
The reversed number is 4, which is not equal to the original number 40. The program will output:
not palindrome

For userNo = 121:
The reversed number is 121, which is equal to the original number 121. The program will output:
palindrome

For userNo = 12321:
The reversed number is 12321, which is equal to the original number 12321. The program will output:
palindrome

Key Points

  • Palindrome Check: The key concept is reversing the number and comparing it to the original number.
  • Negative Numbers: This program doesn’t consider negative numbers. If negative numbers were to be checked, the program would need to handle them separately, since the negative sign would be reversed along with the digits.
  • Zero Case: If userNo = 0, it would be considered a palindrome, as reversing 0 still results in 0.

Leave a Reply