天天看點

入坑Leetcode - 回文數(Palindrome)- No.9

題目:(3) Palindrome

問題描述:

Determine whether an integer is a palindrome. Do this without extra space.

判斷一個整數是否是回文數,沒有額外的空間供你使用。

什麼是回文數?

1.負數一定不是回文數

2.0是回文數

3.正反一樣的數是回文數,例:123321是回文數,1231不是回文數

方法一:

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x >= 0:
            y = str(x)[::-1]
            y = int(y)
            if y == x:
                return True
            else:
                return False
        else:
            return False
           

解題思路:

1.利用題目(2)的翻轉整數判斷

2.注意負數和0

3.有可能還需要注意是否溢出的可能性,此處不需要。

方法二:

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        while x < 0:
            return False
        
        while x >= 0:
            ans = 0
            ans = ans*10 + x%10
            x /= 10
            return ans
        
        if ans == x:
                return True

        else:
            return False
           

解題思路:

1.利用十進制計數法,翻轉整數;

2.利用回文數的特性輸出True和False。