我正在研究 leetcode“762. 二进制表示中设置位的质数”,并且我测试了我的代码在 Jupiter Notebook 上运行良好,当我迁移到 leetcode 时,它显示 null 作为最终结果。有人可以给我任何关于问题所在的提示吗?
class Solution:
def countPrimeSetBits(self, L, R):
"""
:type L: int
:type R: int
:rtype: int
"""
def isPrime(num):
if num == 0:
return False
list1 = list(range(num))
list1.remove(0)
if len(list1) != 0:
list1.remove(num-1)
for i in list1:
if num % (i+1) == 0:
return False
else:
return True
count = 0
for i in range(L, R+1):
newlist = list(bin(i)[2::])
newcount = 0
for j in newlist:
if j == '1':
newcount += 1
if isPrime(newcount) is True:
count += 1
return count
第一个测试用例的预期结果为 23,即 L=842 和 R=888 Jupiter Notebook 按预期返回了 23,但 Leetcode 结果返回 null
最佳答案
你有两个严重的问题。第一个是所提供的代码缩进不正确,因此 countPrimeSetBits()
的代码主体是内部函数 isPrime()
的一部分。第二个问题是,除了是有史以来最糟糕的实现之外,您的 isPrime()
并没有真正起作用:
>>> isPrime(169)
True
>>> 13 * 13
169
>>>
由于这个 else
子句将 return
放置在代码中的错误位置:
else:
return True
下面是您的修补代码,希望在这两种环境中都能工作:
class Solution:
def countPrimeSetBits(self, L, R):
"""
:type L: int
:type R: int
:rtype: int
"""
def isPrime(number):
if number == 0:
return False
divisors = list(range(number))
divisors.remove(0)
if divisors:
divisors.remove(number - 1)
for divisor in divisors:
if number % (divisor + 1) == 0:
return False
return True
count = 0
for i in range(L, R + 1):
newlist = list(bin(i)[2::])
newcount = 0
for j in newlist:
if j == '1':
newcount += 1
if isPrime(newcount):
count += 1
return count
关于python - LeetCode 762 为什么单独的代码在 Jupyter Notebook 中有效,而在 Leetcode 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54465180/