Thursday, September 10, 2015

Palindrome Number | Leetcode

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


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.

---

Solution: Find largest power-10 divisor "pow10" for x (such that 1 <= (x / pow10) <= 9). Using pow10, we can extract the leftmost digit of x. Loop by comparing the leftmost digit and rightmost digit of x until we have no more digits left to compare.
public class Solution {
    public boolean isPalindrome(int x) {
        if (x < 0) return false; // based on question definition
        if (x <= 9) return true; // single digit, no need to check
        
        // Find number of digits.
        int pow10 = 1;
        for (int i = x / 10; i > 0; i /= 10) {
            pow10 *= 10;
        }

        // Loop until there is at most one digit left.
        while (pow10 > 1) {
            int right = x % 10;
            int left = x / pow10;
            if (right != left) return false;
            
            x %= pow10;   // remove left digit
            x /= 10;      // remove right digit
            pow10 /= 100; // we just removed 2 digits
        }
        
        return true;
    }
}

No comments: