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

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

Palindrome Number

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

  • Notes: any negative number is not palindrome.git

  • Example 1:github

Input: 1221
Output: True
  • Example 2:this

Input: -1221
Output: False

思路

  1. 不能使用額外的變量,只能用參數x完成,因爲不能使用額外變量的限制,因此代碼可讀性有點差spa

  2. 將int轉成str,利用len(str)求出整數的位數,而後用str字符串的切片來取得先後對稱部分,如input爲x = 1234len(str(x))爲4,3的下標爲len(str(x))//2.net

  3. 利用python切片能夠快速reverse字符串, a = [1,2,3]a[::-1][3,2,1]code

  4. x = 1234能夠經過判斷12是否等於43來得出是不是迴文,根據上一點12能夠用切片str(x)[ : len(str(x))//2]求得,43能夠根據第4點用str(x)[len(str(x))//2 : ]求得blog

  5. 仍然能夠分爲奇迴文和偶迴文處理,參考閱讀尋找字符串中最長迴文12321以3爲對稱中心,123321以33爲對稱中心leetcode

代碼

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地址字符串

相關文章
相關標籤/搜索