Leetcode866. 回文素数(python)

1. 题目

求出大于或等于 N 的最小回文素数。

回顾一下,如果一个数大于 1,且其因数只有 1 和它自身,那么这个数是素数。

例如,2,3,5,7,11 以及 13 是素数。

回顾一下,如果一个数从左往右读与从右往左读是一样的,那么这个数是回文数。

例如,12321 是回文数。

示例 1:

输入:6
输出:7

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/prime-palindrome
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2 解答

看了别人解答写的,主要是不存在8位数的回文素数,因为8位数的素数只有10_000_019。此外,需要先判断是否是回文(判断快),才看是否是素数。

class Solution:
    def primePalindrome(self, N: int) -> int:
        def isPrime(x):
            if x == 1:
                return False
            for i in range(2,int(x**0.5)+1):
                if x%i == 0:
                    return False
            return True

        def isPalindrome(x):
            x = str(x)
            left = 0
            right = len(x)-1
            while left < right:
                if x[left] != x[right]:
                    return False
                left += 1
                right -= 1
            return True
            
        while True:
            if isPalindrome(N) and isPrime(N):
                break
            N += 1
            if 10**7 < N < 10**8:
                N = 10**8
        return N
发布了510 篇原创文章 · 获赞 152 · 访问量 77万+

猜你喜欢

转载自blog.csdn.net/rosefun96/article/details/105423971
今日推荐