Search code examples
javawhile-loopintjava.util.scannerpalindrome

How to tell if the number is a palindrome or not in Java


I am having trouble figuring out if I am correctly doing the formula for figuring out if a number input by the user is a palindrome or not (also I need to use a while loop). Am I doing the math right? When I trying inputting data it just sits there and does nothing. Here is the code:

System.out.print("Enter the number you would like to be checked if it is a palindrome:");
int num = input.nextInt();
int rev = num % 10;
int count = 1;
int i = 0;
int originalNum = num;

while(count < 2)
    rev = num % 10;
    num = num / 10;
    i = i*10 + rev;

    count = count + 1;
if(originalNum == i)
    System.out.println("The number you input is a palindrome.");
else
    System.out.println("The number you input is not a palindrome.");

Solution

  • I made some changes to your code.Now, it works.

            int num = input.nextInt();
            int rev=0;
            int i = 0;
            int originalNum = num;
    
            while(num!=0){
                rev = num % 10;
                i = i*10 + rev;
                num = num / 10;
            }
    
                if(originalNum == i)
                    System.out.println("The number you input is a palindrome.");
                else
                    System.out.println("The number you input is not a palindrome.");