Python 检查数字是否为回文,但不将其更改为字符串
我遇到了一个问题,如果一个数字Python 检查数字是否为回文,但不将其更改为字符串,python,iteration,palindrome,Python,Iteration,Palindrome,我遇到了一个问题,如果一个数字n是回文,那么只返回True或False 注意:只要有\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。有两个空格 def is_palindrome(n): x, y = n, 0 f = lambda: ____ while x > 0: x, y = ____ , f() return y == n
n
是回文,那么只返回True或False
注意:只要有\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。有两个空格
def is_palindrome(n):
x, y = n, 0
f = lambda: ____
while x > 0:
x, y = ____ , f()
return y == n
我花了大约一个小时在这上面。我发现,将x//10
放在第二个空格将允许函数迭代n
中的位数。然后归结到函数f
理想情况下,每次调用它时,它都应该将n
中的最后一个数字添加到一个新的数字y
。因此,如果n=235
,while循环将迭代3次,每次调用f()
,它应该将5
、3
和2
添加到值y
逻辑如下:(y*10)+x%10
def is_palindrome(n):
x, y = n, 0
f = lambda: (y * 10) + x % 10
while x > 0:
x, y = x//10 , f()
return y == n
print(is_palindrome(123454321))
# True
print(is_palindrome(12))
# False
y*10
将当前y向左移动1位,然后x%10
添加最后一位
print(is_palindrome(235))
# False
迭代前:x=235
,y=0
第一次迭代:x=23
,y=5
第二次迭代:x=2
,y=53
第三次迭代:x=0
,y=532
非常好的解决方案,伙计!也许有一点建议。您的解决方案迭代所有n个数字,但您只需迭代n/2个数字。此外,您可以直接处理负值,因为它们不是回文
def is_palindrome(x):
if x < 0 or (x % 10 == 0 and x != 0):
return False
head, tail = x, 0
while head > tail:
head, tail = head // 10, tail * 10 + head % 10
# When the length is an odd number, we can get rid of the middle digit by tail // 10
return head == tail or head == tail // 10
def是回文(x):
如果x<0或(x%10==0和x!=0):
返回错误
头,尾=x,0
头部>尾部时:
头部,尾部=头部//10,尾部*10+头部%10
#当长度为奇数时,我们可以通过尾//10去掉中间数字
返回头==尾或头==尾//10
时间复杂度:O(log(n)),因为我们在每次迭代中将10除以
空间复杂度:O(1)你说的“需要填充的空格”是什么意思?字符串后半部分的哪些部分不是前半部分的回文?惰性解决方案:x=0
和f=lambda:n如果str(n)==str str(n)[::-1]否则n+1
谢谢你的帮助。另外,你是如何注意到这种模式的。这是你很快就注意到的吗?