本文共 1365 字,大约阅读时间需要 4 分钟。
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121Output: true
Example 2:
Input: -121Output: falseExplanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10Output: falseExplanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
首先负数肯定不是回文数,0`9这种个位的是回文数,其他情况的话就转成字符串判断头尾是否相等就好了
题目最后提到了能否用不转成字符串的方法解决
就是每次mod10求余数可以得到每个位置上的数,然后将数字反转
然后判定是否相等,相等就是回文数,不相等且反转后的数还小于待处理的数,则继续迭代
主要是要注意一下因为回文数有可能是偶数个位数,也有可能是奇数个位数
因此我们判断是否相等的时候得同时判断x和x/10
这x和反转数字更新不同步就会产生一个问题
对于像10,20,30....90这样的两位数10的倍数,除一次之后反转数字是0,更新后数字是9,判断x/10是否等于余数的时候,x/10也是0,解决的方法就是提前判断,可以发现能整除10的数都不是回文数,除了0,因为能整除10必定以0结尾,而0不能作为数字开头
附上两种实现方式
更多leetcode算法题解法请关注我的专栏或关注我
欢迎大家一起套路一起刷题一起ac
class Solution: def isPalindrome(self, x: int) -> bool: if x<0:return False str_x=str(x) if len(str_x)==1:return True for t in range(int(len(str_x)/2)): if str_x[t]!=str_x[-1-t]: return False return True
class Solution: def isPalindrome(self, x: int) -> bool: if x<0 or (x%10==0 and x!=0):return False if x/10<1:return True reverse_num=0 while reverse_num
转载地址:http://hqmrb.baihongyu.com/