题目
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: 4Explanation: 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 <= 18leftandrightconsist of only digits.leftandrightcannot have leading zeros.leftandrightrepresent integers in the range[1, 10^18].leftis less than or equal toright.
题意
定义一个超级回文数n,具有如下性质:n本身是回文数,n的平方根同样是回文数。找到指定范围内所有的超级回文数。
题意
直接构造所有的1e10之内的回文数,判断它们的平方是否在范围内且同样为回文数。注意回文数的长度既可能是奇数也可能是偶数。
思路
Java
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");}}
