SPOJ-下一个回文
Posted
技术标签:
【中文标题】SPOJ-下一个回文【英文标题】:SPOJ-The next palindrome 【发布时间】:2018-08-25 07:42:26 【问题描述】:问题-
https://www.spoj.com/problems/PALIN/
-输入测试用例个数
-输入测试用例
-输出与输入的测试用例最接近的回文数,不包括用例本身
我的尝试-
t=int(input())
while t>0:
k=int(input())
rev=0
while k!=rev:
k=k+1
no=k
rev=0
while no>0:
rev=(rev*10)+(no%10)
no=no//10
if k==rev:
print(k)
t=t-1
问题-
我收到“超出时间限制”,但我无法思考或找到更快的程序。我找到的答案真的很长而且很复杂。
如何修复我的代码?
【问题讨论】:
【参考方案1】:您可以通过将数字视为字符串来节省大量时间,而不仅仅是猜测每个可能的数字并检查它是否是回文:
def next_pal(x):
s = str(x)
if len(s) % 2: # odd
# take the first half (including the middle digit)
first_half = s[:len(s)//2+1]
# construct a number that's that half,
# plus itself reversed (without the middle digit)
candidate = int(first_half + first_half[-2::-1])
# that number could be smaller (e.g. if we started with 245)
if candidate > x:
return candidate
# let's try again: we increment the first half and do the same thing:
new_first_half = str(int(first_half) + 1)
# but be careful: we could be adding a digit here (e.g. 999 -> 100001)
if len(new_first_half) == len(first_half):
return int(new_first_half + new_first_half[-2::-1])
# instead, in those cases, we just return the smallest palindrome of that length
return 10**len(s) + 1
else: # even
# similar dance for even
first_half = s[:len(s)//2]
candidate = int(first_half + first_half[::-1])
if candidate > x:
return candidate
new_first_half = str(int(first_half) + 1)
if len(new_first_half) == len(first_half):
return int(new_first_half + new_first_half[::-1])
return 10**len(s) + 1
注意你有两个循环(我没有计算外部循环,因为没有办法绕过它),而我没有。
【讨论】:
以上是关于SPOJ-下一个回文的主要内容,如果未能解决你的问题,请参考以下文章