Я решаю эту проблему, и описание выглядит так:
Find the largest palindrome made from the product of two n-digit numbers.
Since the result could be very large, you should return the largest palindrome mod 1337.
Example:
Input: 2
Output: 987
Explanation: 99 x 91 = 9009, 9009 % 1337 = 987
Мое текущее решение работает, только если значение n равно 4 или меньше.Я пытался изменить его, но, похоже, мне нужна помощь в выяснении этого.Как мне решить это за меньшее время?Это мой код:
class Solution:
def largestPalindrome(self, n):
"""
:type n: int
:rtype: int
"""
if (n == 1): #it returns '9' if the input is a single digit number
return 9
highest = 0
high = '9'
low = '1'
for k in range(2,n+1):
high = high + '9' #increase the number of digits until 'n' is reached
low = low + '0'
for i in range(int(low), int(high)-1):
for j in range(int(low) + 1, int(high)):
num = str(i * j)
if (int(num) > highest and num == num[::-1]): # if it is a palindrome and highest then
highest = int(num) # highest is the new number
return highest % 1337