一尘不染

下一个回文数

algorithm

我是编程的初学者,所以请您告诉我我的代码有什么问题吗?

如果用户(n)输入的数字不是回文,我想打印下一个回文数

n = int(input("Enter any number :- "))

reverse = 0
temp = n

while (n!=0):
    reverse = reverse * 10
    reverse = reverse + n%10
    n=n//10 
if(temp==reverse):
    print ("Already palindrome:: ")

if(temp != reverse):
     new_temp = temp
     new_reverse = 0
     for i in range(new_temp,new_temp+10):
        while(temp != 0):
            new_reverse = new_reverse * 10
            new_reverse = new_reverse + temp%10
            temp = temp//10
         if(new_temp==new_reverse):
             print ("Next pallindrome is :- ",new_temp)
             break
         if(new_temp != new_reverse):
             temp = new_temp+1

阅读 294

收藏
2020-07-28

共1个答案

一尘不染

您的代码有两个问题。

1)您的“ for i in range”循环将计算temp变量的倒数,但是您无需更改temp变量的值。你做

 new_temp = temp
 for i in range(new_temp,new_temp+10):
    [SNIP]
    if(new_temp != new_reverse):
         temp = new_temp+1 #this value never changes.

因此,您将使用相同的值进行10次迭代。

2)十次迭代可能不足以找到回文。继续走下去,直到找到回文。

工作代码:

def reverse(num):
    reverse= 0
    while num:
        reverse= reverse*10 + num%10
        num= num//10
    return reverse

num= int(input("Enter any number :- "))
if num==reverse(num):
    print ("Already palindrome.")
else:
    while True:
        num+= 1
        if num==reverse(num):
            print ("Next palindrome is : %s"%num)
            break
2020-07-28