Home | Projects | Notes > Problem Solving > LC - E - 762. Prime Number of Set Bits in Binary Representation (bit manipulation)
This solution uses bitwise operations.
Complexity Analysis:
[left, right]
, and
Solution:
xxxxxxxxxx
461bool isPrime(int n);
2int countBits(int n);
3
4int countPrimeSetBits(int left, int right){
5 int count = 0;
6
7 while (left <= right)
8 {
9 if (isPrime(countBits(left)))
10 count++;
11
12 left++;
13 }
14
15 return count;
16}
17
18int countBits(int n)
19{
20 int count = 0;
21
22 while (n)
23 {
24 n &= (n - 1); // clear lowest set bit
25 count++;
26 }
27
28 return count;
29}
30
31bool isPrime(int n)
32{
33 int i;
34
35 // 1 is not a prime number
36 if (n == 1)
37 return false;
38
39 for (i = 2; i < n; i++)
40 {
41 if (n % i == 0)
42 return false;
43 }
44
45 return true;
46}