问题-
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
问题-
我正在“超出时间限制”,但是我无法思考或找到更快的程序。我发现的答案确实漫长而复杂。
如何修复我的代码?
答案 0 :(得分:0)
通过将数字视为字符串,您不仅可以猜测每个可能的数字并检查它是否是回文,还可以节省大量时间:
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
请注意您有两个循环(我没有计算外部循环,因为没有办法解决),而我没有一个循环。