Skip to content

Commit 0849185

Browse files
committed
Add solution #866
1 parent 6496e0c commit 0849185

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -673,6 +673,7 @@
673673
863|[All Nodes Distance K in Binary Tree](./0863-all-nodes-distance-k-in-binary-tree.js)|Medium|
674674
864|[Shortest Path to Get All Keys](./0864-shortest-path-to-get-all-keys.js)|Hard|
675675
865|[Smallest Subtree with all the Deepest Nodes](./0865-smallest-subtree-with-all-the-deepest-nodes.js)|Medium|
676+
866|[Prime Palindrome](./0866-prime-palindrome.js)|Medium|
676677
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
677678
868|[Binary Gap](./0868-binary-gap.js)|Easy|
678679
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|

solutions/0866-prime-palindrome.js

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/**
2+
* 866. Prime Palindrome
3+
* https://leetcode.com/problems/prime-palindrome/
4+
* Difficulty: Medium
5+
*
6+
* Given an integer n, return the smallest prime palindrome greater than or equal to n.
7+
*
8+
* An integer is prime if it has exactly two divisors: 1 and itself. Note that 1 is not a prime
9+
* number.
10+
* - For example, 2, 3, 5, 7, 11, and 13 are all primes.
11+
*
12+
* An integer is a palindrome if it reads the same from left to right as it does from right to left.
13+
* - For example, 101 and 12321 are palindromes.
14+
*
15+
* The test cases are generated so that the answer always exists and is in the range [2, 2 * 108].
16+
*/
17+
18+
/**
19+
* @param {number} n
20+
* @return {number}
21+
*/
22+
var primePalindrome = function(start) {
23+
while (true) {
24+
const numStr = start.toString();
25+
if (numStr.length % 2 === 0 && start > 11) {
26+
start = 10 ** Math.ceil(Math.log10(start + 1));
27+
continue;
28+
}
29+
if (!isPalindrome(numStr)) {
30+
start++;
31+
continue;
32+
}
33+
if (isPrime(start)) return start;
34+
start++;
35+
}
36+
};
37+
38+
function isPrime(num) {
39+
if (num <= 1) return false;
40+
if (num <= 3) return true;
41+
if (num % 2 === 0 || num % 3 === 0) return false;
42+
for (let i = 3; i <= Math.sqrt(num) + 1; i += 2) {
43+
if (num % i === 0) return false;
44+
}
45+
return true;
46+
}
47+
48+
function isPalindrome(str) {
49+
let left = 0;
50+
let right = str.length - 1;
51+
while (left < right) {
52+
if (str[left++] !== str[right--]) return false;
53+
}
54+
return true;
55+
}

0 commit comments

Comments
 (0)