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)
-----------------------------------------------------------------------------------------------------------------
My code is
import math
class Solution:
def next_palin(self, n):
# the smallest palindome >= n
s = str(n)
l = len(s)
head = s[:(l // 2)]
head_mid = s[:((l + 1) // 2)]
tail = s[((l + 1) // 2):]
new_head_mid = head_mid if (head[::-1] >= tail) else str(int(head_mid) + 1) #bug2: head > tail[::-1], example, 7670
# bug4: if you want to find the smallest palindome > n, just make n+=1
# You could not update head[::-1] >= tail as head[::-1] > tail.
# The bug is 9 99 999, the str length between and after should be same
res = new_head_mid + new_head_mid[:(l//2)][::-1] #bug1: _head[::-1]
return res
def is_palin(self, n):
return str(n) == str(n)[::-1]
def superpalindromesInRange(self, L, R):
l, r = int(L), int(R)
cur,upper = math.ceil(math.sqrt(l)), math.floor(math.sqrt(r)) #bug3: ceil floor
res = 0
cur = int(self.next_palin(cur))
while (cur <= upper):
if (self.is_palin(cur * cur)):
res += 1
cur += 1
cur = int(self.next_palin(cur))
return res
s = Solution()
#print(s.superpalindromesInRange("1","2"))
print(s.next_palin("7008"))
print(s.next_palin("7006"))
print(s.next_palin("7118"))
print(s.next_palin("9"))