leetcode:479. 最大回文数乘积(python3解法,数学相关算法题)
难度:简单
给定一个整数 n ,返回 可表示为两个
n
位整数乘积的 最大回文整数 。因为答案可能非常大,所以返回它对1337
取余 。示例 1:
输入:n = 2 输出:987 解释:99 x 91 = 9009, 9009 % 1337 = 987示例 2:
输入:n = 1 输出:9提示:
1 <= n <= 8
题解:
class Solution:def largestPalindrome(self, n: int) -> int:if n == 1:return 9 # 1位数的最大回文数是9# 生成 n 位数的最大值max_num = int("9" *n) # 例如,n=3时,max_num = 999min_num = 10 ** (n - 1) # n位数的最小值,即100max_palindrome = 0 # 储存找到的最大回文数# 从最大 n 位数开始逆序遍历for i in range(max_num, min_num-1, -1):for j in range(i, min_num-1, -1): # j 从 i 开始,以减少重复计算product = i * j# 检查乘积是否为回文if str(product) == str(product)[::-1]:max_palindrome = max(max_palindrome, product) # 更新最大回文数break # 找到的最大回文数可立即使用return max_palindrome % 1337 # 返回结果对1337取余