LeetCode 866. Prime Palindrome

原题链接在这里:https://leetcode.com/problems/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.

题解:

For palindrome, only odd number length could be prime.

Because all even length could be divided by 11. like 1111 % 11 = 0.

Check all odd length palindrome, if it is prime, return it.

AC Java:

 1 class Solution {
 2     public int primePalindrome(int N) {
 3         if(N >= 8 && N <= 11){
 4             return 11;
 5         }
 6         
 7         for(int i = 1; i <= 100000; i++){
 8             String half = "" + i;
 9             String can = half + new StringBuilder(half.substring(0, half.length() - 1)).reverse().toString();
10             
11             int canVal = Integer.valueOf(can);
12             if(canVal >= N && isPrime(canVal)){
13                 return canVal;
14             }
15         }
16         
17         return -1;
18     }
19     
20     private boolean isPrime(int n){
21         if(n < 2 || n % 2 == 0){
22             return n == 2;
23         }
24         
25         for(int i = 3; i * i <= n; i += 2){
26             if(n % i == 0){
27                 return false;
28             }
29         }
30         
31         return true;
32     }
33     
34 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12185508.html