题目: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
代码:
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()
思考: