Skip to content

Commit ca59d96

Browse files
committed
different method to count number of set bits implemented
1 parent c5949b6 commit ca59d96

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

General Programs/SetBits.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,44 @@
33
//program to count number of set bits
44
using namespace std;
55

6+
/*
7+
1) Using & operator right shift operation
8+
2) Using __buildtin_popcount(n) function to get count of set bits
9+
3)Brian Kernighan’s Algorithm:
10+
*/
11+
12+
//program to count no of bits
13+
int CountBits(int n)
14+
{
15+
int count=0;
16+
while(n)
17+
{
18+
n >>= 1; //simply right shift the no by 1
19+
count++;
20+
}
21+
22+
return count;
23+
}
24+
25+
26+
int CountSet(int n)
27+
{
28+
int count=0;
29+
while(n)
30+
{
31+
count += n & 1;
32+
n >>= 1; //simply right shift the no by 1
33+
34+
}
35+
36+
return count;
37+
}
38+
639
int main()
740
{
41+
//cout<<CountSet(10);
42+
int n = __builtin_popcount(7);
43+
44+
cout<<n;
845
return 0;
946
}

0 commit comments

Comments
 (0)