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)
解題思路(思路進階過程);
1. 遍歷數字1到sqrt(stoll(R)) , 判斷自身是否迴文數且平方數是否迴文數;
TLE , 因爲有很多數自身不是迴文數,產生無效判斷 ;
class Solution {
public:
int superpalindromesInRange(string L, string R)
{
int res = 0 ;
long long lnum = stoll(L) , rnum = stoll(R) ;
for(long long i = 1 ; i <= (long long)sqrt(rnum) ; ++i)
{
if(!ispalin(i)) continue ;
long long square = i * i ;
if(ispalin(square) && square >= lnum && square <= rnum) res++ ;
}
return res ;
}
bool ispalin(long long i)
{
string s = to_string(i) ;
if(s.size() == 1) return true ;
for(int i = 0 , j = s.size() - 1 ; i <= j ; ++i , --j)
{
if(s[i] != s[j]) return false ;
}
return true ;
}
};
2 . 構造sz位數的迴文數 , 範圍從[ to_string(sqrt(left)).size() , min(9 , to_string(sqrt(right)).size())] , 因爲本身是迴文數,如果其平方數也是迴文數,則res++ ;
class Solution {
public:
int superpalindromesInRange(string L, string R)
{
lnum = stoll(L) ;
rnum = stoll(R) ;
int res = 0 ;
long long sqrtr = sqrt(rnum) + 1 , sqrtl = sqrt(lnum) ;
string sqrtrs = to_string(sqrtr) , sqrtls = to_string(sqrtl) ;
for(int sz = sqrtls.size() ; sz <= min(9 ,(int)sqrtrs.size()) ; ++sz)
{
string s(sz , '.') ;
DFS(0 , sz , s , res) ;
}
return res ;
}
bool ispalin(string s)
{
if(s.empty() || s.size() == 1) return true ;
for(int i = 0 , j = s.size() - 1 ; i <= j ; ++i , --j)
{
if(s[i] != s[j]) return false ;
}
return true ;
}
void DFS(int pos , int sz , string& s , int& res)
{
if(pos > sz - 1 - pos)
{
long long num = stoll(s) ;
long long squanum = num * num ;
if( squanum < lnum || squanum > rnum) return ;
string squas = to_string(squanum) ;
if(ispalin(squas))
{
res++ ;
}
return ;
}
for(int i = (pos == 0 ? 1 : 0) ; i < 10 ; ++i)
{
s[pos] = '0' + i ;
s[sz - 1 - pos] = '0' + i ;
DFS(pos + 1 , sz , s , res) ;
}
}
private :
long long lnum , rnum ;
};