难度:简单
给定一个整数 n ,返回 可表示为两个
n位整数乘积的 最大回文整数 。因为答案可能非常大,所以返回它对1337取余 。示例 1:
输入:n = 2 输出:987 解释:99 x 91 = 9009, 9009 % 1337 = 987示例 2:
输入:n = 1 输出:9提示:
1 <= n <= 8
题解:
pythonclass Solution: def largestPalindrome(self, n: int) -> int: if n == 1: return 9 # 1位数的最大回文数是9 # 生成 n 位数的最大值 max_num = int("9" *n) # 例如,n=3时,max_num = 999 min_num = 10 ** (n - 1) # n位数的最小值,即100 max_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取余
leetcode:479. 最大回文数乘积(python3解法,数学相关算法题)
心软且酷丶2025-05-31 12:10
相关推荐
南境十里·墨染春水9 小时前
C++ 工厂模式:从入门到进阶,彻底掌握对象创建的艺术@insist1239 小时前
系统架构设计师-实时性评价、调度算法与内核架构选型某人辛木9 小时前
Web自动化测试C+++Python9 小时前
详细介绍一下Java泛型的通配符小帅热爱难回头10 小时前
编写Skill生成AI落地项目系统架构diving deep11 小时前
脚本速览-python2601_9516437712 小时前
Python第一,Java跌出前三,C语言杀回来了AC赳赳老秦14 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源一只齐刘海的猫15 小时前
【Leetcode】找到字符串中所有字母异位词