我正在解决这个leetcode问题,描述就像这样,
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
答案 0 :(得分:0)
你可以通过摆脱不必要的案件来加速这一点。对于初学者:
另一种方法:不是循环通过i和j,而是循环可能的回文。从具有2n位数的最大可能回文开始,并测试是否可以将其表示为两个n位数的乘积;如果你对可能因素设定的界限一定要小心,这不应该要求检查很多情况。如果可以表达为产品,那么你就完成了;如果没有,请尝试下一个回文,然后重复,直到找到有用的东西。