To solve this problem, we need to determine the palindrome number that results from repeatedly adding a given number to its reverse until a palindrome is obtained, along with the number of steps taken to reach that palindrome.
Approach
- Check for Palindrome: A helper function to check if a number is a palindrome by converting it to a string and verifying if it reads the same forwards and backwards.
- Reverse Number: Another helper function to reverse the digits of a number by converting it to a string, reversing the string, and converting it back to an integer.
- Iterative Addition: Start with the given number and repeatedly add it to its reverse until a palindrome is found. Count the number of steps taken during this process.
Solution Code
def is_palindrome(n):
s = str(n)
return s == s[::-1]
def reverse_number(n):
return int(str(n)[::-1])
n = int(input())
current = n
steps = 0
while not is_palindrome(current):
current += reverse_number(current)
steps += 1
print(current, steps)
Explanation
- Palindrome Check: The function
is_palindromeconverts the number to a string and checks if it is the same as its reverse (using slicings[::-1]). - Reverse Number: The function
reverse_numberreverses the digits of the number by converting it to a string, reversing the string, and converting it back to an integer. - Iterative Process: We start with the input number and keep adding its reverse to itself until we get a palindrome. Each addition counts as one step. Once a palindrome is found, we print the palindrome and the number of steps taken.
This approach efficiently handles the problem using string operations for palindrome checks and reversals, which are straightforward and easy to implement. The use of Python's arbitrary-precision integers ensures that we can handle large numbers without overflow issues.
Example: For input 1776, the steps are:
- 1776 + 6771 = 8547 (step 1)
- 8547 + 7458 = 16005 (step 2)
- 16005 + 50061 = 66066 (step 3, palindrome)
Output: 66066 3
This solution is optimal and works for all valid inputs that eventually form a palindrome. The time complexity depends on the number of steps needed to reach a palindrome, which varies by input but is generally small for most cases. The space complexity is O(1) (excluding input storage) since we only keep track of the current number and step count.


作者声明:本文包含人工智能生成内容。