题目

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.

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

解答

这道题,首先要判断一个数是不是回文数,那我们就定义一个函数来反转一个数:

import numpy as np  
  
def reverse_number(x):  
    res = 0  
    while x > 0:  
        i = x % 10  
        x = (x - i) // 10  
        res = res * 10 + i  
    return res  
  
reverse_number2 = np.vectorize(reverse_number)

最后这句,将这个函数向量化,这样可以应用于numpy的array。

有了这个反转数字的函数,那判断是不是回文数就非常简单了:

def is_palindrome(x):  
    return x == reverse_number2(x)

能够判断回文数了,那我们就可以给一个数组,把回文数给提取出来,更进一步,直接把最大值给返回来:

def max_palindrome(x):  
    y = x[is_palindrome(x)]  
    if np.size(y) == 0:  
        return None  
    else:  
        return np.max(y)

有了这些函数,那这道题就很简单。

def largest_palindrome_product(N):  
    res = 0  
    x = np.arange(N // 10,N)   
    for i in x:  
        max = max_palindrome(x * i)  
        if max is not None and res < max:  
            res = max  
      
    return res