2012年1月14日星期六

Palindrome Number


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.



    public boolean isPalindrome(int x) {
        if(x < 0) return false;
        int numOfDigits = 1;
        int base = 1;
        while(x / base > 9) {
            base *= 10;
            ++numOfDigits;
        }
     
        int head, tail;
        for(int i = 0; i < numOfDigits / 2; ++i) {
            head = x / base;
            tail = x % 10;
            if(head != tail) return false;
            x -= head * base;
            x /= 10;
            base /= 100;
        }
        return true;
    }

没有评论:

发表评论