Determine whether an integer is a palindrome. Do this without extra space.
解答 : 有的答案是把数转成字符串,逆序之后与原来的相等,那么就是回文数;本人提供的答案是,设置两个指针,分别指向头部和尾部,对比对应的数是否相等,直到指针指向中间位置,结束。
class Solution(object):
def isPalindrome(self, x):"""
:type x: int
:rtype: bool
"""
str_list = str(x) # 数转str list
length = len(str_list) # 字符串长度
if length <= 1: # 如果输入的数字长度为1,那么返回True
return True
else:
i = 0 # 定义头指针指向数组头部
j = length-1 # 定义尾指针指向数组尾部
while(i < j): # 尾部指针大于头部指针
if str_list[i] != str_list[j]: # 若不想等,直接跳出程序
return False
else: # 头指针右移,尾指针左移
i += 1
j -= 1
return True