每日一道算法题之LeetCode9

LeetCode9 回文数

题目:https://leetcode-cn.com/problems/palindrome-number/

解题思路如下:

# 判断一个整数是否是回文数。
# 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
# 1先判断,若为负,返回false;
# 2把数字转换为列表,进行翻转;翻转后的列表再转换回数字;
# 3然后判断转换前后的2个数字是否相等。
 1 class Solution:
 2     def isPalindrome(self, x: int) -> bool:
 3         if x < 0:
 4             return False
 5         xnew = list(str(x))
 6         xnew.reverse()
 7         xnew = int(''.join(xnew))
             return x == xnew
 8         #if x == xnew:
 9         #   return True
10         #else:
11         #   return False
#看了一道别人的题解,写的挺好的,记录一下。
# 1先转换为字符串,计算其长度
# 2取长度的一半,判断字符串左右两边是否相等。
# 注:左--从左往右,右--从右往左
1 class Solution:
2     def isPalindrome(self, x: int) -> bool:
3         s = str(x)
4         n = len(s)
5         h = n // 2
6         return s[0:h] == s[-1:-h-1:-1]

注:关于字符串的索引,正索引和负索引不一样。

原文地址:https://www.cnblogs.com/vvzhang/p/14319636.html