How to reverse and add a number until you get a palindrome in Python?

Here is a simple solution that will reverse and add a number until the result is a palindrome in python :

def reverse_and_add(n):
    def is_palindrome(n):
        # Convert the number to a string and check if it is equal to its reverse
        return str(n) == str(n)[::-1]

    # Keep track of the number of iterations needed
    iterations = 0
    while not is_palindrome(n):
        # Reverse the number and add it to itself
        n += int(str(n)[::-1])
        iterations += 1
    return (n, iterations)
print(reverse_and_add(1234))  # Output: (5555, 1)

This function takes an integer as input and returns a tuple containing the palindrome and the number of iterations needed to obtain it. The is_palindrome function is a helper function that checks if a number is a palindrome by converting it to a string and checking if it is equal to its reverse. The main loop keeps track of the number of iterations needed and reverses and adds the number until the result is a palindrome.

Leave a Comment