LeetCode - Palindrome Number

来源:互联网 发布:独立域名商城 编辑:程序博客网 时间:2024/06/11 13:10

LeetCode - Palindrome Number

The problem is described as following:

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 solvedthe 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.

My solution is as following:

class Solution:    # @param x, an integer    # @return a boolean    def isPalindrome(self, x):        if x < 0:            return False        if x < 10:            return True        div = 1        while x/div >= 10:            div *= 10        while x != 0:            left = x / div            right = x % 10            if left == right:                x = (x % div) / 10                div /= 100            else:                return False        return True

题目比较简单,考虑到空间限制,只需要多一个div变量,实现每次取最左和最右一位比较即可。

0 0
原创粉丝点击