LeetCode解题之Palindrome Number
原题
判断一个int型数字是否是回文形式,不许用额外的空间。
注意点:
- 负数都是不回文数
- 不许用额外的空间
例子:
输入: x=123
输出: False
输入: x=12321
输出: True
解题思路
既然是判断是否是回文数,那就依次获取数的首尾两个数判断是否相等。先通过for循环来获取数字的最高位,这样就可以从头开始获取每个数字,通过%操作从末尾获取每个数字。为了方便操作,可以把比较过的数字去除掉。需要注意的是,去掉首尾后,原来的最高位要除以100,而不是10。
AC源码
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
div = 1
while x / div >= 10:
div *= 10
while x > 0:
l = x // div
r = x % 10
if l != r:
return False
x %= div
x //= 10
div /= 100
return True
if __name__ == "__main__":
assert Solution().isPalindrome(123) == False
assert Solution().isPalindrome(12321) == True
assert Solution().isPalindrome(-121) == False
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。