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;
}
};