forked from ravya1108/hactoberfest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count_no_of_set_bits_5_methods.cpp
148 lines (117 loc) · 2.39 KB
/
count_no_of_set_bits_5_methods.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// C++ program to Count set
# Method 1
// bits in an integer
#include <bits/stdc++.h>
using namespace std;
/* Function to get no of set bits in binary
representation of positive integer n */
unsigned int countSetBits(unsigned int n)
{
unsigned int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
/* Program to test function countSetBits */
int main()
{
int i;
cin>>i;
cout << countSetBits(i);
return 0;
}
/*
# Method 2
// cpp implementation of recursive approach to find the
// number of set bits in binary representation of positive
// integer n
#include <bits/stdc++.h>
using namespace std;
// recursive function to count set bits
int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
// if last bit set add 1 else add 0
return (n & 1) + countSetBits(n >> 1);
}
// driver code
int main()
{
int n;
cin >> n;
// function calling
cout << countSetBits(n);
return 0;
}
*/
/*
# Method 3
// C++ program to Count set
// bits in an integer
#include <iostream>
using namespace std;
class count{
/* Function to get no of set bits in binary
representation of passed binary no. */
public:
unsigned int countSetBits(int n)
{
unsigned int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
};
*/
/*
# Method 4
// CPP implementation for recursive
// approach to find the number of set
// bits using Brian Kernighan’s Algorithm
#include <bits/stdc++.h>
using namespace std;
// recursive function to count set bits
int countSetBits(int n)
{
// base case
if (n == 0)
return 0;
else
return 1 + countSetBits(n & (n - 1));
}
*/
/*
# Method 5
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
int BitsSetTable256[256];
// Function to initialise the lookup table
void initialize()
{
// To initially generate the
// table algorithmically
BitsSetTable256[0] = 0;
for (int i = 0; i < 256; i++)
{
BitsSetTable256[i] = (i & 1) +
BitsSetTable256[i / 2];
}
}
// Function to return the count
// of set bits in n
int countSetBits(int n)
{
return (BitsSetTable256[n & 0xff] +
BitsSetTable256[(n >> 8) & 0xff] +
BitsSetTable256[(n >> 16) & 0xff] +
BitsSetTable256[n >> 24]);
}
*/