[Leetcode]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.

判斷一個數是不是迴文串~可以直接判斷翻轉的數字和原數字是否相同,但是要注意翻轉數字可能會導致溢出,但python會自動處理整數溢出的情況~

class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        if x < 0: return False
        reverse, tmp = 0, x
        while tmp:
            reverse, tmp = reverse * 10 + tmp % 10, tmp / 10
        return reverse == x

還有一種方法,每次比較數字的第一位和最後一位看是否相等,然後去掉這兩位繼續循環比較~

class Solution:
    # @return a boolean
    def isPalindrome(self, x):
        if x < 0: return False
        k = 1
        while x / k >= 10: k *= 10
        while x:
            if x / k != x % 10: return False
            x = (x - x / k * k) / 10
            k /= 100
        return True


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章