回文数判断

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.

 

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        div = 1
        while x/div >= 10:
            div *= 10
        x_tmp = x
        while x_tmp > 0:
            i = x_tmp % 10
            j = x_tmp / div
            if i != j:
                return False
            x_tmp = x_tmp % div / 10
            div /= 100
        return True

 

posted on 2017-10-11 16:20  Peyton_Li  阅读(143)  评论(0编辑  收藏  举报

导航