本文實例講述了Python實現判斷一個整數是否為回文數算法。分享給大家供大家參考,具體如下:
第一個思路是先將整數轉換為字符串,再將字符串翻轉并與原字符串做比較
def isPalindrome(self, x): """ :type x: int :rtype: bool """ #思路:先將整數轉換為字符串,再將字符串翻轉并與原字符串做比較 x = str(x) return x == x[::-1]
代碼簡潔
第二個思路,嘗試著不用字符串,將整數直接拆除一個數組,再比較這個數組是否“對稱”
def isPalindrome(self, x): """ :type x: int :rtype: bool """ #思路二:將數字轉換成數組 #負數肯定不是回文數 if x < 0 : return False elif x <= 9: return True else: nums = [] while x >= 10 : mod = x % 10 nums.append(mod) x = x/10 nums.append(x) print "nums:",nums for i in range(0,len(nums)/2): if nums[i] != nums[-1-i]: return False return True
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答