The Next Palindrome number

前端 未结 11 1820
走了就别回头了
走了就别回头了 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:35

    If it helps, I believe it's possible to solve this problem with n/2 iterations where n is the length of the input number. Here's my solution in Python:

    def next_palin_number(number):
        number+=1
        # Convert the number to a list of its digits.
        number = list(str(number))
        # Initialize two indices for comparing symmetric digits.
        i = 0
        j = len(number) - 1
        while i < j:
            # If the digits are different:
            if number[i] != number[j]:
                # If the lower-power digit is greater than the higher-power digit:
                if int(number[j]) > int(number[i]):
                    if number[j-1]!='9':
                        number[j - 1] = str(int(number[j - 1]) + 1)
                        number[j] = number[i]
                    else:
                        number = list(str(int(''.join(number[:j]))+1))+number[j:]
                else:
                    number[j] = number[i]
            i += 1
            j -= 1
        # Concatenate and return the result.
        return "".join(number)
    

提交回复
热议问题