判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
PS:
你能不将整数转为字符串来解决这个问题吗?
一刷:
时间复杂度O(logn),空间复杂度O(1),但是这个解法最少循环1次最多循环1.5次,可以进行优化
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
i = 1
quotient = x
while(quotient != 0):
i *= 10
quotient = x // i
remainder1, quotient2 = x, x
while(i != 1):
i //= 10
quotient1, remainder1 = divmod(remainder1, i)
quotient2, remainder2 = divmod(quotient2, 10)
if quotient1 != remainder2:
return False
return True
可以反转一半的数字进行比较,停止条件为当前数字大于没反转的部分。这样每次循环0.5次就能得出结果了
class Solution:
def isPalindrome(self, x: int) -> bool:
# 极端情况
if x < 0:
return False
if x == 0:
return True
if x % 10 == 0:
return False
reverse = 0
quotient = x
while(quotient > reverse):
quotient, remainder = divmod(quotient, 10)
reverse = reverse*10 + remainder
print(reverse,quotient)
if quotient == reverse:
return True
elif reverse // 10 == quotient:
return True
else:
return False