The Next Palindrome number

前端 未结 11 1754
走了就别回头了
走了就别回头了 2021-01-17 07:23

I am beginner in programming, So can you please tell me what\'s wrong with my code?

I want to print next palindrome number if the number entered by the user (n) is n

11条回答
  •  滥情空心
    2021-01-17 07:40

    There are two problems with your code.

    1) Your "for i in range" loop calculates the reverse of the temp variable, but you don't change the temp variable's value. You do

     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.
    

    So you're making 10 iterations with one and the same value.

    2) Ten iterations might not be enough to find a palindrome. Keep going until you find a palindrome.

    Working code:

    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
    

提交回复
热议问题