LeetCode 题解工作台

回文质数

给你一个整数 n ,返回大于或等于 n 的最小 回文质数 。 一个整数如果恰好有两个除数: 1 和它本身,那么它是 质数 。注意, 1 不是质数。 例如, 2 、 3 、 5 、 7 、 11 和 13 都是质数。 一个整数如果从左向右读和从右向左读是相同的,那么它是 回文数 。 例如, 101 和…

category

2

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·结合·number·theory

bolt

答案摘要

class Solution: def primePalindrome(self, n: int) -> int:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·结合·number·theory 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数 n ,返回大于或等于 n 的最小 回文质数

一个整数如果恰好有两个除数:1 和它本身,那么它是 质数 。注意,1 不是质数。

  • 例如,23571113 都是质数。

一个整数如果从左向右读和从右向左读是相同的,那么它是 回文数

  • 例如,10112321 都是回文数。

测试用例保证答案总是存在,并且在 [2, 2 * 108] 范围内。

 

示例 1:

输入:n = 6
输出:7

示例 2:

输入:n = 8
输出:11

示例 3:

输入:n = 13
输出:101

 

提示:

  • 1 <= n <= 108
lightbulb

解题思路

方法一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

回文质数题解:数学·结合·number·theory | LeetCode #866 中等