LeetCode 题解工作台
回文质数
给你一个整数 n ,返回大于或等于 n 的最小 回文质数 。 一个整数如果恰好有两个除数: 1 和它本身,那么它是 质数 。注意, 1 不是质数。 例如, 2 、 3 、 5 、 7 、 11 和 13 都是质数。 一个整数如果从左向右读和从右向左读是相同的,那么它是 回文数 。 例如, 101 和…
2
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数学·结合·number·theory
答案摘要
class Solution: def primePalindrome(self, n: int) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·number·theory 题型思路
题目描述
给你一个整数 n ,返回大于或等于 n 的最小
一个整数如果恰好有两个除数:1 和它本身,那么它是 质数 。注意,1 不是质数。
- 例如,
2、3、5、7、11和13都是质数。
一个整数如果从左向右读和从右向左读是相同的,那么它是 回文数 。
- 例如,
101和12321都是回文数。
测试用例保证答案总是存在,并且在 [2, 2 * 108] 范围内。
示例 1:
输入:n = 6 输出:7
示例 2:
输入:n = 8 输出:11
示例 3:
输入:n = 13 输出:101
提示:
1 <= n <= 108
解题思路
方法一
class Solution:
def primePalindrome(self, n: int) -> int:
def is_prime(x):
if x < 2:
return False
v = 2
while v * v <= x:
if x % v == 0:
return False
v += 1
return True
def reverse(x):
res = 0
while x:
res = res * 10 + x % 10
x //= 10
return res
while 1:
if reverse(n) == n and is_prime(n):
return n
if 10**7 < n < 10**8:
n = 10**8
n += 1
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the candidate’s understanding of prime number theory and palindrome detection.
- question_mark
Pay attention to optimization strategies for both checking and searching for prime palindromes.
- question_mark
Evaluate their approach to handling large inputs efficiently under the constraint of 10^8.
常见陷阱
外企场景- error
Failing to optimize the prime checking process, leading to slow solutions.
- error
Not validating palindrome properties correctly, resulting in incorrect outputs.
- error
Using brute force without considering performance optimizations when searching for the smallest prime palindrome.
进阶变体
外企场景- arrow_right_alt
Finding the nth prime palindrome instead of just the smallest.
- arrow_right_alt
Limiting the solution to prime palindromes within a certain range.
- arrow_right_alt
Generalizing to find prime palindromes of even or odd length only.