Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ca59d96

Browse files
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

Lines changed: 37 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /