LeetCode——866.回文素数
生活随笔
收集整理的這篇文章主要介紹了
LeetCode——866.回文素数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
分析,這個題目本身不難,用數學方法很容易解出來,問題是當給的數據過大時,容易超時。
數學法:遍歷所有數字,檢查是不是回文串。如果是,檢查是不是素數,如果當前數字長度為 8,可以跳過檢查,因為不存在 8 長度的素數。
用于自行調試的.java文件
class primePalindrome866 {public static void main(String[] args) {int num = 9989900;System.out.println(primePalindrome(num));}public static int primePalindrome(int N) {while(true){if(isPalindrome(N) && isPrime(N))return N;N++;if (10_000_000 < N && N < 100_000_000)N = 100_000_000;}}public static boolean isPalindrome(int N){if(N==0){return true;}else if(N%10==0){return false;}//下面是N>0且不為10的整數倍的情況int M = 0;int temp = N;while(temp!=0){M=M*10+temp%10;temp=temp/10;}return M==N;}public static boolean isPrime(int N) {if (N < 2) return false;int R = (int) Math.sqrt(N);for (int d = 2; d <= R; ++d)if (N % d == 0)return false;return true;} }總結
以上是生活随笔為你收集整理的LeetCode——866.回文素数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Future源码解读
- 下一篇: JQuery Datatables 服务