LSGO——LeetCode實戰:9題 迴文數(Palindrome Number)

原題

判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。

示例 1:

輸入: 121
輸出: true
示例 2:

輸入: -121
輸出: false
解釋: 從左向右讀, 爲 -121 。 從右向左讀, 爲 121- 。因此它不是一個迴文數。
示例 3:

輸入: 10
輸出: false
解釋: 從右向左讀, 爲 01 。因此它不是一個迴文數。
進階:

你能不將整數轉爲字符串來解決這個問題嗎?

解法一:

  • 思路:使用列表記錄整數的數字,直接將列表反轉查看是否是迴文數
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        ans=[]
        if x < 0:
            return False
        while x!=0:
            ans.append(x%10) 
            x = x//10
        result =0
        if ans == ans[::-1]:
            return True
        return False

解法二:(反轉一半的數字)

將原整數的後一半進行反轉,如果整數的數字個數爲奇數的話,就需要將ans值除以10(這樣剔除中間數字的影響)

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

解法三(整數的左右比較)

思路:將整數兩端的數字進行比較,如果全部相同則是迴文數

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
       while x>0:
           left = x//div
           right = x%10
           if right != left:
               return False
           x = (x%div) //10
           div = div //100
           
           
       return True
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章