题目描述:
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.
思路:
比较暴力一点的就是转成string方法,不过这样很简单没什么意义。如果不用转换string方法,我们可以先计算这个数字的位数,然后通过取余并乘上10的位数减1次方。这样就可以计算出最后的结果。直接上代码!
代码:
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
num = x
check = x
res = 0
c = 0
while x > 0:
x = x // 10
c += 1
while num > 0:
res += (num % 10) * (10**(c-1))
num = num // 10
c -= 1
if res == check:
return True
else:
return False
知识点:
求一个数的位数,一是转换成string然后用len()求,二就是这种方法。
c = 0 while x > 0: x = x // 10 c += 1