Skip to content

Commit 36f6672

Browse files
authored
Create prime-number-of-set-bits-in-binary-representation.cpp
1 parent 20cd087 commit 36f6672

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(log(R - L)) = O(1)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
int countPrimeSetBits(int L, int R) {
7+
static const unordered_set<uint32_t> primes{2, 3, 5, 7, 11, 13, 17, 19};
8+
int result = 0;
9+
for (int i = L; i <= R; ++i) {
10+
result += primes.count(bitCount(i));
11+
}
12+
return result;
13+
}
14+
15+
private:
16+
int bitCount(uint32_t n) {
17+
int count = 0;
18+
for (; n; n &= n - 1) {
19+
++count;
20+
}
21+
return count;
22+
}
23+
};

0 commit comments

Comments
 (0)