LeetCode 866. Prime Palindrome

866. Prime Palindrome(回文素数)

题目:

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

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

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

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

  例如,12321 是回文数。

思路:

  思路还是挺清晰的,从给入数字向上检索,如果既是回文数,又是素数,就直接输出,如果不满足条件,那么就增加数字,继续判断。

  这里有一个小问题,就是所有偶数位的回文数,都可以被11整除,至于证明。。。。。咱也不知道,咱也不敢问,所有如果发现这个数是偶数位,那么直接进一位,首数字和尾数字全为1,继续判断。

代码:

 1     public static int primePalindrome(int N) 
 2     {
 3         if (N <= 2) 
 4             return 2;
 5         else if(N <= 3)
 6             return 3;
 7         else if(N <= 5)
 8             return 5;
 9         else if(N <= 7)
10             return 7;
11         else if(N <= 11)
12             return 11;
13         
14         for (int i = N; ; ) 
15         {
16             if(isHui(i) && isPrime(i))
17                 return i;
18             
19             if((i + "").length() % 2 == 0)
20                 i = (int)(Math.pow(10, (i + "").length()) + 1);           
21             else
22                 i++;
23             
24         }
25     }
26     
27     public static boolean isPrime(int i)
28     {
29         for (int j = 2; j <= Math.sqrt(i); j++)
30             if (i % j == 0) 
31                 return false;
32         return true;
33     }
34     
35     public static boolean isHui(int s)
36     {
37         String str = s+"";
38         int len = str.length();
39         for (int j = 0; j < len/2; j++) 
40             if (str.charAt(j) != str.charAt(len-j-1)) 
41                 return false;
42         return true;
43     }
View Code
原文地址:https://www.cnblogs.com/blogxjc/p/10895244.html