【发布时间】:2018-06-12 19:52:46
【问题描述】:
我正在解决这个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
【问题讨论】:
标签: python-3.x palindrome