判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
进阶: 不将整数转为字符串来解决这个问题
链接:https://leetcode-cn.com/problems/palindrome-number
转换成字符串就比较容易:
class Solution:
def isPalindrome(self, x: int) -> bool:
return (True if str(x) == str(x)[::-1] else False)
不转成字符串的话,首先想到的是将数字反转,然后将反转后的数字与原始数字进行比较:
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
y = x
res = 0
while y:
last = y%10
res = res*10+last
y//=10
if res==x:
return True
else:
return False
看了官方标答,原来还有反转一半数字这种骚操作。
如何反转后半部分的数字:对于数字 1221,如果执行 1221 % 10,我们将得到最后一位数字 1,要得到倒数第二位数字,我们可以先通过整除以 10 把最后一位数字从 1221 中移除,1221 //10 = 122,再求出上一步结果除以 10 的余数,122 % 10 = 2,就可以得到倒数第二位数字。如果我们把最后一位数字乘以 10,再加上倒数第二位数字,1 * 10 + 2 = 12,就得到了我们想要的反转后的数字。如果继续这个过程,我们将得到更多位数的反转数字。
如何知道反转数字的位数已经达到原始数字位数的一半:我们将原始数字除以 10,然后给反转后的数字乘上 10,所以,当原始数字小于反转后的数字时,就意味着我们已经处理了一半位数的数字。
链接:https://leetcode-cn.com/problems/two-sum/solution/hui-wen-shu-by-leetcode/
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0 or (x>0 and x%10==0):
return False
y = 0
while x>y:
y = y*10+x%10
x //= 10
return x==y or x==y//10
来源:https://blog.csdn.net/lxx199603/article/details/99692971