Leetcode Super Palindromes Next Palindrome

231 篇文章 0 订阅
120 篇文章 1 订阅

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)

-----------------------------------------------------------------------------------------------------------------

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"))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值