Leetcode每日一刷-9(回文数)

第一种 逐个比较

class Solution:
  def isPalindrome(self, x):
    if not isinstance(x, int) or x < 0:
      return False
    x = str(x)
    i = 0
    j = len(x) - 1
    # 从头开始与从尾开始一一比较,i小于j的时候(长度为奇数中间不用相比)反之继续
    while i < j:
      if x[i] == x[j]:
        i += 1
        j -= 1
      else:
        return False
    return True

num = 181
sol = Solution()
sol.isPalindrome(num)

 

第二种 整个全体反转比较

class Solution:

  def isPalindrome(self, x):
    if not isinstance(x, int) or x < 0:
      return False
    elif str(x) == str(x)[::-1]:
      return True
    else:
      return False

x = -181
sol = Solution()
sol.isPalindrome(x)

posted @ 2019-04-18 17:34  寒南  阅读(70)  评论(0编辑  收藏  举报