Palindrome Number

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

public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0)
            return false; 

        //div can faciliate finding the value of the most significant digit
        int div = 1;
        while (x/div >= 10) {
            div *= 10;
        }

        while (x != 0) {
            int left = x/div;
            int right = x%10;
            if (left != right)
                return false; 

            x = (x%div)/10;
            div = div/100; //divide 100, not 10!
        }

        return true; 

    }
}
Advertisements

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