-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSetBits.cpp
68 lines (57 loc) · 879 Bytes
/
SetBits.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<iostream>
//program to count number of set bits
using namespace std;
/*
1) Using & operator right shift operation
2) Using __buildtin_popcount(n) function to get count of set bits
3)Brian Kernighan’s Algorithm:
*/
//program to count no of bits
int CountBits(int n)
{
int count=0;
while(n)
{
n >>= 1; //simply right shift the no by 1
count++;
}
return count;
}
int countSetUsing(int n)
{
int count= 0 ;
while(n)
{
n &= (n-1);
count++;
}
return count;
}
int CountSet(int n)
{
int count=0;
while(n)
{
count += n & 1;
// n >>= 1; //simply right shift the no by 1
//right shift is equivalent to division by 2
n /= 2;
}
return count;
}
//int countUnset(int n){
//
// int count = 0;
// while(n)
// {
// count += n | 1;
//
// n /= 2;
// }
//}
int main()
{
cout<<countSetUsing(19);
// cout<<endl<<countUnset(5);
return 0;
}