A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
The first line contains integer t, the number of test cases. Followed by t lines containing integers K.
For each K, output the smallest palindrome larger than K.
Input:
2
808
2133
Output:
818
2222
import math def helper(word): word_new = '' # check is the length of character list is even or odd if len(word) % 2 == 1: for i in range(len(word)//2 + 1): word_new += str(word[i]) word_new += word_new[:len(word)//2 ][::-1] else: for i in range(len(word)//2): word_new += str(word[i]) word_new += word_new[::-1] return word_new def solve(word, n): string = ''.join([str(x) for x in word]) z = helper(word) if z > string: return z else: # increase the middle character(s) and return the pallindrome inc = 1 for i in range(math.ceil(len(word)/2) - 1,-1,-1): word[i] += inc inc = word[i]//10 word[i] %= 10 return helper(word) N = int(input()) for i in range(N): word = list(map(int, input())) word_len = len(word) # for cases like '999','99999' if len(set(word))==1 and word[0]==9: print('1'+'0'*(word_len-1)+'1') else: print(solve(word, word_len))
Question Link – Link
In Python, the print() function is a fundamental tool for displaying output. While printing simple…
Python is a versatile programming language known for its simplicity and flexibility. When working on…
PDF (Portable Document Format) files are commonly used for sharing documents due to their consistent…
PDF (Portable Document Format) files are widely used for document exchange due to their consistent…
Python is a high-level programming language known for its simplicity and ease of use. However,…
Object-Oriented Programming (OOP), iterators, generators, and closures are powerful concepts in Python that can be…
This website uses cookies.