9. Palindrome Number
2017-10-26 本文已影响5人
ciantian
最近再刷leetcode,除了链表之外的都用python 实现,贴出一些代码,希望指正.
问题描述:
Determine whether an integer is a palindrome. Do this without extra space.
判断一个整数是不是水仙花数,考虑超界.
解决方案
取长度,从前后进行遍历,判断是不是相同,不相同直接中断.
代码如下
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
length = len(str(x))
y = x
# print(length)
for i in range(length//2):
tmp1 = (int(x / pow(10, length - i-1)))
x = x % pow(10, length - i-1)
tmp = y // (pow(10, i))
tmp2 = (tmp % 10)
# print("i:",i)
# print("length - i:", length - i)
# print("tmp1", tmp1)
# print("tmp2",tmp2)
if tmp1 != tmp2:
return False
return True
solution = Solution()
print(solution.isPalindrome(1001))