Let's say a positive integer is a superpalindrome if it is a palindrome, and it is also the square of a palindrome.
Now, given two positive integers L
and R
(represented as strings), return the number of superpalindromes in the inclusive range [L, R]
.
Example 1:
Input: L = "4", R = "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.
Note:
1 <= len(L) <= 18
1 <= len(R) <= 18
L
andR
are strings representing integers in the range[1, 10^18)
.int(L) <= int(R)
思路:枚举10000内的数字,构造成回文串,再平方以后继续判断。
主要构造回文串的两种方式。偶数项和奇数项
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+8;
const int mod=1e9+7;
class Solution {
public:
#define LL long long
bool check(string s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j--)
if (s[i] != s[j])
return false;
return true;
}
int superpalindromesInRange(string L, string R) {
LL l = stoll(L), r = stoll(R);
int ans = 0;
for (int j = 1; j <= 3; j++) {
if (j * j >= l && j * j <= r)
ans++;
}
for (int i = 1; i < 10000; i++) {
string t = to_string(i);
string rt = t;
reverse(rt.begin(), rt.end());
LL s = stoll(t + rt);
s *= s;
if (s > r)
break;
if (check(to_string(s)) && l <= s && s <= r)
ans++;
for (char j = '0'; j <= '9'; j++) {
s = stoll(t + j + rt);
s *= s;
if (check(to_string(s)) && l <= s && s <= r)
ans++;
}
}
return ans;
}
};