一.问题描述
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121 Output: true
Example 2:
Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10 Output: false Explanation: 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算法题解法请关注我的专栏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<x:
reverse_num=reverse_num*10+x%10
x=int(x/10)
if x==reverse_num or int(x/10) ==reverse_num:
return True
return False
博客围绕判断整数是否为回文数的算法题展开。先提出问题,接着给出两种解题思路,一是将整数转成字符串判断头尾是否相等;二是不转字符串,通过取余反转数字来判断。还指出要注意回文数位数奇偶及特殊情况,最后附上源码。
5951

被折叠的 条评论
为什么被折叠?



