algorithm notes: leetcode#762 prime number of set bits in binary representation

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
9
class :
def countPrimeSetBits(self, L, R):
"""
:type L: int
:type R: int
:rtype: int
"""
prime_set = {2, 3, 5, 7, 11, 13, 17, 19}
return sum(bin(n).count('1') in prime_set for n in range(L, R+1))

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
class {
public int countPrimeSetBits(int L, int R) {
Set<Integer> prime_set = new HashSet<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19));
int ans = 0;
for(int n = L; n <= R; n++){
if(prime_set.contains(Integer.bitCount(n))){
ans ++;
}
}
return ans;
}
}

Time complexity

O(N).

Space complexity

O(1).


762. Prime Number of Set Bits in Binary Representation
(中文版) 算法笔记: 力扣#762 二进制表示中质数个计算置位