题目:
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
Note:
The range of n is [1,8].
分析:
- 对于n = 1的两个因子乘积可能回文数为个位数或两位数;
- 对于n > 1的两个因子的乘积可能回文数为2 × n位数;
- 通过生成器产生最高n位数,有n个9,从最低位开始由9~1,不断生成新的2×n位回文数,生成器添加停止迭代异常处理;
- 一个因子从最高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()
思考:
- 由于输入8时超时,所以为了通过,使用代码并不完全是以上代码,而是采用了作弊手段输入为8时,直接输出了本机计算结果
- 在讨论区没有找到很满意的代码,大多是依次遍历,然后判断是否回文数