Skip to content

Commit f5cbc85

Browse files
committed
🎉 feat: initial commit for leetcode 762 using bitset
1 parent 737a379 commit f5cbc85

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
762. Prime Number of Set Bits in Binary Representation
2+
Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.
3+
(Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.)
4+
Example 1:
5+
Input: L = 6, R = 10
6+
Output: 4
7+
Explanation:
8+
6 -> 110 (2 set bits, 2 is prime)
9+
7 -> 111 (3 set bits, 3 is prime)
10+
9 -> 1001 (2 set bits , 2 is prime)
11+
10->1010 (2 set bits , 2 is prime)
12+
Example 2:
13+
Input: L = 10, R = 15
14+
Output: 5
15+
Explanation:
16+
10 -> 1010 (2 set bits, 2 is prime)
17+
11 -> 1011 (3 set bits, 3 is prime)
18+
12 -> 1100 (2 set bits, 2 is prime)
19+
13 -> 1101 (3 set bits, 3 is prime)
20+
14 -> 1110 (3 set bits, 3 is prime)
21+
15 -> 1111 (4 set bits, 4 is not prime)
22+
Note:
23+
L, R will be integers L <= R in the range [1, 10^6].
24+
R - L will be at most 10000.
25+
26+
题目大意:给两个数L和R,在[L, R]区间寻找数字的二进制中1的个数是素数的数字个数
27+
分析:R不超过106次方,也就是不超过220次方,那么判断是否为素数只需判断是否等于2 3 5 7 11 13 17 19即可,用bitset也只需20位表示即可,用count函数计算1的个数,然后用cnt统计后返回~
28+
29+
class Solution {
30+
public:
31+
int countPrimeSetBits(int L, int R) {
32+
int cnt = 0, hash[20] = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1};
33+
for (int i = L; i <= R; i++) {
34+
bitset<20> b(i);
35+
if(hash[b.count()]) cnt++;
36+
}
37+
return cnt;
38+
}
39+
};

0 commit comments

Comments
 (0)