Palindrome Integer

Given an integer, determine if it is a palindrome number.


There are a couple of methods in approaching this problem. The first thing that comes to mind is to convert the integer into a string, use the charAt method to compare significant characters and move towards the middle. Obviously a working solution and definitely worth talking about, but quite bland. We can come up with quite an elegant solution with a little math, specifically, floor, log10, pow, and mod.

Let's talk a bit about these methods, floor, log10, pow, and mod first. When used in combination, floor and log10 computes the length of an integer minus one. For example, rounding down the log base 10 of 243342 will yield the length of 5. The more succinct programmatic expression of this statement is Math.floor(Math.log10(243342)). If desired, add 1 to that and you get the length of the integer. What's the big deal, you can find the length of a number with some math. What's the use in that? This is when the pow method comes in. With the pow method, we can exponentiate the base to the length of the integer minus one. In our example, this yields 100000. We can divide 243342 by 100000 to get the most significant digit (left most digit). Compare that to the least significant digit (right most digit), which can be obtained using the mod method. The integer is not a palindrome if the left most and right most digits do not match up.

The next step is to move towards the middle of the integer by trimming the significant digits and repeat the above process. Trimming the most significant digit is achieved by modding the given integer by denominator, which yields 43342. Trimming the least significant digit is achieved by dividing the given integer by the base, which yields 4334.


public static boolean isPalindrome(int x) {
    if(x < 0) x *= -1;

    int n = Math.floor(Math.log10(x)) + 1;
    while(x > 0) {
        int msb = x / Math.pow(10, n - 1);
        int lsb = x % 10;

        if(msb != lsb)
            return false;

        x %= Math.pow(10, n - 1);
        x /= 10;
        n - 2;

    return true;

This article is my 28th oldest. It is 370 words long, and it’s got 0 comments for now.