标签:amp class ann 指定 erp lan ros positive mesi
Let‘s say a positive integer is a super-palindrome if it is a palindrome, and it is also the square of a palindrome.
Given two positive integers left
and right
represented as strings, return the number of super-palindromes integers in the inclusive range [left, right]
.
Example 1:
Input: left = "4", right = "1000"
Output: 4
Explanation: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.
Example 2:
Input: left = "1", right = "2"
Output: 1
Constraints:
1 <= left.length, right.length <= 18
left
and right
consist of only digits.left
and right
cannot have leading zeros.left
and right
represent integers in the range [1, 10^18]
.left
is less than or equal to right
.定义一个超级回文数n,具有如下性质:n本身是回文数,n的平方根同样是回文数。找到指定范围内所有的超级回文数。
直接构造所有的1e10之内的回文数,判断它们的平方是否在范围内且同样为回文数。注意回文数的长度既可能是奇数也可能是偶数。
class Solution {
private int count = 0;
public int superpalindromesInRange(String left, String right) {
long a = Long.parseLong(left), b = Long.parseLong(right);
count = 0;
dfs("", a, b);
for (int i = 0; i <= 9; i++) {
dfs(String.valueOf(i), a, b);
}
return count;
}
private void dfs(String s, long left, long right) {
if (s.length() > 9) return;
if (s.length() > 0) {
long x = Long.parseLong(s);
if (x * x > right) return;
if (s.charAt(0) != ‘0‘ && x * x >= left && isPalindrome(x) && isPalindrome(x * x)) count++;
}
for (int i = 0; i <= 9; i++) {
dfs(i + s + i, left, right);
}
}
private boolean isPalindrome(long x) {
char[] s = String.valueOf(x).toCharArray();
int i = 0, j = s.length - 1;
while (i < j) {
if (s[i++] != s[j--]) return false;
}
return true;
}
public static void main(String[] args) {
Solution s = new Solution();
s.superpalindromesInRange("4", "1000");
}
}
标签:amp class ann 指定 erp lan ros positive mesi
原文地址:https://www.cnblogs.com/mapoos/p/14746893.html