不使用任何額外變量判斷迴文數字(6行代碼)

不使用任何額外變量判斷迴文數字

Palindrome Number

  • Determine whether an integer is a palindrome. Do this without extra space.
  • Notes: any negative number is not palindrome.

  • Example 1:

Input: 1221
Output: True
  • Example 2:
Input: -1221
Output: False

思路

  1. 不能使用額外的變量,只能用參數x完成,由於不能使用額外變量的限制,所以代碼可讀性有點差
  2. 將int轉成str,利用len(str)求出整數的位數,然後用str字符串的切片來取得前後對稱部分,如input爲x = 1234len(str(x))爲4,3的下標爲len(str(x))//2
  3. 利用python切片可以快速reverse字符串, a = [1,2,3]a[::-1][3,2,1]
  4. x = 1234可以通過判斷12是否等於43來得出是否是迴文,根據上一點12可以用切片str(x)[ : len(str(x))//2]求得,43可以根據第4點用str(x)[len(str(x))//2 : ]求得
  5. 仍然可以分爲奇迴文和偶迴文處理,參考閱讀尋找字符串中最長迴文12321以3爲對稱中心,123321以33爲對稱中心

代碼

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        if x < 0:
            return False
        if len(str(x)) % 2 == 0:
            return int(str(x)[ : len(str(x))//2]) == int(str(x)[len(str(x))//2 : ][ : :-1])
        else:
            return int(str(x)[ : len(str(x))//2+1]) == int(str(x)[len(str(x))//2 : ][ : :-1])

本題以及其它leetcode題目代碼github地址: github地址

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