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)
就是遍历所有开根号后的数(直接遍历原始string范围太大了,开个方自后就比较小了,类似于https://leetcode.com/problems/consecutive-numbers-sum/description/),比赛的时候就知道本地打个表就可以过了,
class Solution:
def superpalindromesInRange(self, L, R):
"""
:type L: str
:type R: str
:rtype: int
"""
n=len(R)
nn1=max((len(L)+1)//2,1)
nn2=(len(R)+1)//2
L,R=int(L),int(R)
res=0
for i in xrange(nn1 if nn1%2 else nn1+1,nn2+1,2):
j=i//2+1
s,t='1'+'0'*(j-1),'9'+'0'*(j-1)
for t in range(int(s), int(t)+1):
t2=int(str(t)+str(t)[:-1][::-1])
t3=t2*t2
t4=str(t3)
if t4==t4[::-1] and L<=t3<=R:
# print(t3)
res+=1
for i in xrange(nn1+1 if nn1%2 else nn1,nn2+1,2):
j=i//2
s,t='1'+'0'*(j-1),'9'+'0'*(j-1)
for t in range(int(s), int(t)+1):
t2=int(str(t)+str(t)[::-1])
t3=t2*t2
t4=str(t3)
if t4==t4[::-1] and L<=t3<=R:
# print(t3)
res+=1
return res
Python3这个解法会TLE,Python2可以AC,如果Py3要过,可以进一步减小遍历的范围
left = int(math.floor(math.sqrt(L)))
right = int(math.ceil(math.sqrt(R)))
L, R = int(L), int(R)
left = int(math.floor(math.sqrt(L)))
right = int(math.ceil(math.sqrt(R)))
n1 = len(str(left))
n2 = len(str(right))