Palindrome Number

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:
Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem “Reverse Integer”, you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.

This problem goes to the simple problem of how you get one bit from a decimal number. lets say the input number is 8976, if you want to get bit 4, first you do 10^4 = 1000, then, 8796/1000 = 8.
What if you want to access some bit in the middle, say I want bit 1 from left (9), it is the same, first you get to 10, then get to next bit 100, then you use 8796%100 = 96, then use the same method 96/10 = 9.

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0)
            return false;
        long power = 1;
        while(power < x) {
            power *= 10;
        }
        long start = power/10;
        int end = 1;
        while(start >= end) {
            if ((x/start) != ((x%(end*10))/end)) // geting the end th bit from right
                return false;
            x -= (x/start)*start; // remove MSB after checked
            start /= 10;
            end *= 10;
            
        }
        return true;
    }
}

Use the reverse number method, reverse the input number and then compare with the original input, notice we use long to prevent overflow.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s