不使用任何额外变量判断回文数字

不使用任何额外变量判断回文数字

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

相关文章
相关标签/搜索