906. Super Palindromes

88 篇文章 0 订阅
42 篇文章 0 订阅

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. 1 <= len(L) <= 18
  2. 1 <= len(R) <= 18
  3. L and R are strings representing integers in the range [1, 10^18).
  4. 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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值