leet479. Largest Palindrome Product

题目:python

Find the largest palindrome made from the product of two n-digit numbers.git

Since the result could be very large, you should return the largest palindrome mod 1337.code

Example:ip

Input: 2get

Output: 987input

Explanation: 99 x 91 = 9009, 9009 % 1337 = 987string

Note:it

The range of n is [1,8].io

分析:class

  1. 对于n = 1的两个因子乘积可能回文数为个位数或两位数;
  2. 对于n > 1的两个因子的乘积可能回文数为2 × n位数;
  3. 经过生成器产生最高n位数,有n个9,从最低位开始由9~1,不断生成新的2×n位回文数,生成器添加中止迭代异常处理;
  4. 一个因子从最高n位因子开始尝试,能被回文数整除则返回真,不然递减,直到另外一个因子大于该因子;

代码:

class Solution(object):
    def largestPalindrome(self, n):
        """
        :type n: int
        :rtype: int
        """
        def genDecNum(digitals):
            ret = 0
            bits = len(digitals) * 2
            if bits == 2 and digitals[0] == 0:
                return 9
            for i,x in enumerate(digitals):
                ret += x * (10 ** i + 10 ** (bits - 1 - i))
            return ret
        def foundFactor(digitals):
            num = genDecNum(digitals)
            bits = len(digitals) * 2
            maxFactor = 10 ** (bits // 2) - 1
            # print "num:" + str(num) + "fact:" + str(maxFactor)
            while maxFactor * maxFactor >= num:
                factor2 = 0
                # print "num:" + str(num) + "fact0" + str(num // maxFactor) + "fact:" + str(maxFactor)
                if num % maxFactor == 0:
                    return [maxFactor,num // maxFactor]
                maxFactor -= 1
            return [-1,-1]
        def getdigts(n):
            maxNum = 10 ** n - 1
            minNum = 0
            num = maxNum
            while num >= minNum:
                yield [(num // (10 ** i)) % 10 for i in range(n)][::-1]
                num -= 1
        g = getdigts(n)
        nums = g.next()
        ret = foundFactor(nums)
        try:
            while ret[0] < 0 and nums:
                nums = g.next()
                ret = foundFactor(nums)
                # print ret
        except StopIteration:
            return -1

        if ret[0] > 0:
            return (ret[0] * ret[1]) % 1337
        else:
            return 0





def stringToInt(input):
    return int(input)


def intToString(input):
    if input is None:
        input = 0
    return str(input)


def main():
    import sys
    def readlines():
        for line in sys.stdin:
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = lines.next()
            n = stringToInt(line)

            ret = Solution().largestPalindrome(n)

            out = intToString(ret)
            print out
        except StopIteration:
            break


if __name__ == '__main__':
    main()

思考:

  1. 因为输入8时超时,因此为了经过,使用代码并不彻底是以上代码,而是采用了做弊手段输入为8时,直接输出了本机计算结果
  2. 在讨论区没有找到很满意的代码,大可能是依次遍历,而后判断是否回文数