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?
不用转化成字符串的方法
一种笨方法,Runtime: 188 ms
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if x < 10:
return True
nums = []
while True:
x,rem = divmod(x,10)
nums.append(rem)
if x < 10:
nums.append(x)
break
lenth = len(nums)
for i in range(lenth-1):
if nums[i] != nums[lenth-i-1]:
return False
return True
leetcode字符外的解法就是反转后看与原来的数字是否一致,试了下Runtime: 172 ms
本文介绍了一种不通过转换为字符串来判断整数是否为回文数的方法,并提供了两种实现方式,一种是逐位比较,另一种是通过反转整数进行对比。
842

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



