版权声明:转载请注明出处 https://blog.csdn.net/sixkery/article/details/83216851
给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。
(注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。)
示例 1:
输入: L = 6, R = 10
输出: 4
解释:
6 -> 110 (2 个计算置位,2 是质数)
7 -> 111 (3 个计算置位,3 是质数)
9 -> 1001 (2 个计算置位,2 是质数)
10-> 1010 (2 个计算置位,2 是质数)
示例 2:
输入: L = 10, R = 15
输出: 5
解释:
10 -> 1010 (2 个计算置位, 2 是质数)
11 -> 1011 (3 个计算置位, 3 是质数)
12 -> 1100 (2 个计算置位, 2 是质数)
13 -> 1101 (3 个计算置位, 3 是质数)
14 -> 1110 (3 个计算置位, 3 是质数)
15 -> 1111 (4 个计算置位, 4 不是质数)
注意:
- L, R 是 L <= R 且在 [1, 10^6] 中的整数。
- R - L 的最大值为 10000。
解答
from math import sqrt
class Solution(object):
def countPrimeSetBits(self, L, R):
"""
:type L: int
:type R: int
:rtype: int
"""
alist = list(range(L,R+1))
count = 0
for i in alist:
n = bin(i).count('1')
if self.is_prime(n):
count += 1
return count
def is_prime(self,n):
# 对正整数 n,如果用 2 到 sqrt(n) 之间的所有整数去除,均无法整除,则 n 为质数
if n == 1:
return False
for i in range(2,int(sqrt(n))+1):
if n % i == 0:
return False
return True
题目涉及到质数的判断,但是这样写时间复杂度为 O(n^2)。显然还有更加优化的代码。
题目说 L, R 是 L <= R 且在 [1, 10^6] 中的整数,所以在这里边,置位最大为 19 ,也就是说只能在 0-19 之间的质数。
看大佬代码:
class Solution(object):
def countPrimeSetBits(self, L, R):
"""
:type L: int
:type R: int
:rtype: int
"""
# L,R 是在 [1,10^6] 中的整数,因此置位的个数最多为 19
#创建列表 p,0-20 中质数为置 1 ,非质数位置 0
p = (0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1)
re = 0
for n in range(L, R + 1):
re += p[bin(n).count('1')]
return re
re = Solution().countPrimeSetBits(6,10)
print('re=',re)
时间复杂度 O(n)