LeetCode 866: Prime Palindrome
Problem Description
Explanation:
To find the smallest prime palindrome greater than or equal to a given number n
, we can iterate through numbers starting from n
and check if each number is a palindrome and a prime number. We can implement functions to check for palindromes and prime numbers, and then use these functions to find the desired number.
Algorithm:
- Start iterating from
n
and check each number if it is a palindrome and a prime number. - Check if a number is a palindrome by converting it to a string and comparing the reverse string with the original string.
- Check if a number is a prime number by iterating from 2 to the square root of the number and checking if it has any divisors.
- Return the first number that satisfies both conditions.
Time Complexity:
The time complexity of this approach is O(sqrt(n) * log(n)), where n is the input number.
Space Complexity:
The space complexity of this approach is O(1).
: :
Solutions
class Solution {
public int primePalindrome(int n) {
while (true) {
if (isPalindrome(n) && isPrime(n)) {
return n;
}
n++;
if (10000000 < n && n < 100000000) {
n = 100000000;
}
}
}
private boolean isPalindrome(int num) {
String str = String.valueOf(num);
return new StringBuilder(str).reverse().toString().equals(str);
}
private boolean isPrime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Related LeetCode Problems
Loading editor...