DEV Community

integervis
integervis

Posted on

Palindrome with % and / [Java]

You can use different ways to find out if a number is palindrome using string conversion. I want to explore here an algorithm with a while loop in Java using modulo operator and integer division.

A number is palindrome if it is the same when reading it from left to right and right to left. As an example:

  • 1331 is a palindrome;
  • 1234 is not.

Therefore we need to find the reversed number and check if it’s equal to the original one.

A while loop is perfect for this scenario. We are going to take the original number and deconstruct it in its original digits. We will use these to rebuild the reversed numbner.

Before going to the solution there are a couple of properties we need to mention first:

Modulo operator returns the remainder of a division hence, if we have a number %10 we will have the last digit of that number. No rounding will happen.

1123 MOD 10 = 3
1124 MOD 10 = 4
Enter fullscreen mode Exit fullscreen mode

This is the main tool we will use to grab the last digits of any integer number.

Integer division will discard the remainder. So any integer divided by 10 will simply provide the remaining number and remove the last digit.

This step is important to provide a different number so that in the next iteration the remainder will be correct.

Below the solution including all of the logics we mentioned above:


public class Palindrome {
    public static void main(String[] args) {

        // hard-coding my numbers for ease of use
        int num = 1771;
        int temp = num;

        int reversedNumber = 0;

        while (temp > 0) {

            // MOD division to get the last digit
            int lastDigit = temp % 10;

            // reversed number built by adding the last digit 
            // to the previous last digit multiplied by 10. 
            // We are shifting the numbers.
            reversedNumber = reversedNumber * 10 + lastDigit;

            // integer division that will equal to 0 
            // if the number is < 10 and 
            // consequently stopping the while loop.
            temp = temp/10; 
        }

        if (num == reversedNumber) {
            System.out.println("It is a palindrome");
        } else {
            System.out.println("It is not a palindrome");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

I am fascinated by the logics within the loop but let me know what you think of this approach.

Top comments (0)