Wednesday, April 22, 2015

Palindrome Number

Problem:
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:
class Solution {
public:
    // No need to use count function.
    // Mistake was, I used count function earlier, this is a bug. you need divide divisor by 100 in each loop. Test case: 1000021.
    int count(int x) {
        int digit_count = 0;
        int tmp = x;
        while (tmp != 0) {
            digit_count++;
            tmp /= 10;
        }
        return digit_count;
    }
    bool isPalindrome(int x) {
        if (x < 0)
            return false;
        //int dig_cnt = count(x);
        //x = abs(x);
        int divisor = 1, tmp = x;
        while (tmp/10 != 0) {
            divisor *= 10;
            tmp = tmp/10;
        }
        
        while (x != 0) {
            int last_dig = x/divisor;
            int first_dig = x % 10;
            if (last_dig != first_dig)
                return false;
            x = (x % divisor)/10;
            divisor /= 100;
        }
        return true;
    }
};

No comments:

Post a Comment