python – Palindrome来自两个3位数字的乘积

我想找到通过两个3位数字相乘得到的最大回文.

我开始时a和b均为999,并且在发生的每次乘法时递减a和b.

a = 999 #Defining Variables
b = 999

for i in range (1000): 
    c= a*b                          #multiply a to b
    if int(str(c)[::-1]) == c:
        print c
    a = a-1                         #decrement the value of a
    c=a*b                           #multiply a by the decremented a
    if int(str(c)[::-1]) == c:
        print c

    b = b-1                         #decrement b so that both a and b have been decremented

结果出现了698896,289982,94249,69696 ……其中698896是第一个数字.目前我还在试图找出我所缺少的东西.

解决方法:

你不能以交替的方式递减a和b,因为你错过了a = 999和b = 997这样的值对.

尝试嵌套循环,从999开始并向后计数.

就像是

def is_pal(c):
    return int(str(c)[::-1]) == c

maxpal = 0
for a in range(999, 99, -1):
    for b in range(a, 99, -1):
        prod = a * b
        if is_pal(prod) and prod > maxpal:
            maxpal = prod

print maxpal

编辑:保罗评论后修改下限.

上一篇:LeetCode 9. Palindrome Number


下一篇:LeetCode 214. Shortest Palindrome