首页 > 其他 > 详细

LeetCode 866. Prime Palindrome

时间:2019-05-20 17:32:38      阅读:97      评论:0      收藏:0      [点我收藏+]

题目:

  求出大于或等于 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

 

LeetCode 866. Prime Palindrome

原文:https://www.cnblogs.com/blogxjc/p/10895244.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!