LeetCode: 867. Prime Palindrome

LeetCode: 867. Prime Palindrome

题目描述

Find the smallest prime palindrome greater than or equal to N.
Recall that a number is prime if it’s only divisors are 1 and itself, and it is greater than 1.

For example, 2,3,5,7,11 and 13 are primes.
Recall that a number is a palindrome if it reads the same from left to right as it does from right to left.
For example, 12321 is a palindrome.

Example 1:

Input: 6
Output: 7

Example 2:

Input: 8
Output: 11

Example 3:

Input: 13
Output: 101

Note:

1 <= N <= 10^8
The answer is guaranteed to exist and be less than 2 * 10^8.

解题思路

回文数可以表示为 a[n-1]*10^(n-1) + a[n-2]*10^(n-2) + ... + a[0]*10^0
a[n-1] = a[0] 因此,原式可表示为 a[n-1]*(10^(n-1) + 10^0) + a[n-2]*(10^(n-2) + 10^2) + ...,

n 为偶数时, 原式为 a[n-1]*(10^(n-1) + 10^0) + a[n-2]*(10^(n-2) + 10^2) + ... + a[n/2]*(10^(n/2) + 10^(n/2-1))
(10^(n-k-1) + 10^k) = (10^(n-k-2) - 10^(n-k-3) + ... + 10^k) * 11, 因此,当 n 为偶数时, 原式能被 11 整除。

因此,本题可以直接暴力求解,剪去位数为偶数的分支,以节省时间。

AC 代码

class Solution {
    // 判断 num 是否是素数
    bool isPrime(int num)
    {
        if(num < 2) return false;

        for(int i = 2; i <= sqrt(num); ++i)
        {
            if(num % i == 0) return false;
        }

        return true;
    }
    // 判断 num 是否是回文数
    bool isPalindrome(int num)
    {
        string orgNumStr = to_string(num);
        string reverseNumStr(orgNumStr.rbegin(), orgNumStr.rend());

        return (orgNumStr == reverseNumStr);
    }
public:
    int primePalindrome(int N) {
        while(!isPalindrome(N) || !isPrime(N))
        {
            ++N;

            // 跳过偶数位数, 偶数位的回文数都能被 11 整除
            if(N > pow(10, 1) && N < pow(10, 2) && N != 11) N = pow(10, 2);
            if(N > pow(10, 3) && N < pow(10, 4)) N = pow(10, 4);
            if(N > pow(10, 5) && N < pow(10, 6)) N = pow(10, 6);
            if(N > pow(10, 7) && N < pow(10, 8)) N = pow(10, 8);
        }

        return N;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值