【问题标题】:Find the largest palindrome made from the product of two n-digit numbers - python找到由两个 n 位数字的乘积组成的最大回文 - python
【发布时间】: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


    【解决方案1】:

    您可以通过消除不必要的情况来大大加快速度。对于初学者:

    • 因为两个整数的顺序无关紧要,您只需要考虑 j >= i 的情况,因此您可以将 j 循环的下限设置为 j=i。 (或者可能更高;见下文。)
    • 因为您正在寻找最大的回文,您可以通过将 i 和 j 从最高值循环到最低值而不是从最低值到最高值循环来节省大量时间。对于每个 i,您可以在找到第一个(最高)j 给出 i*j = 回文数后立即停止 j 循环,因为任何较低的 j 值都会给出更小的回文数。
    • 您可以使用迄今为止最高的回文数来设置更智能的 j 下限。检查任何小于最高/i 的 j 值是没有意义的,因为即使这些确实给你一个回文,它也会比你已经拥有的要小。

    另一种方法:不是循环通过 i 和 j,而是循环可能的回文。从最大可能的 2n 位回文开始,测试是否可以将其表示为两个 n 位数字的乘积;如果您小心设置可能因素的界限,则不需要检查很多情况。如果 if 可以表示为一个产品,那么你就完成了;如果没有,请尝试下一个回文,然后重复,直到找到可行的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2020-05-24
      • 2014-01-31
      相关资源
      最近更新 更多