Skip to content

Commit 16522eb

Browse files
committed
Number of 1 Bit using C++
1 parent 9bdafbe commit 16522eb

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Bit Manipulation/Number_of_1_Bits.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
2+
/* Given a positive integer N, print count of set bits in it.
3+
4+
Example 1:
5+
6+
Input:
7+
N = 6
8+
Output:
9+
2
10+
Explanation:
11+
Binary representation is '110'
12+
So the count of the set bit is 2.*/
13+
#include<bits/stdc++.h>
14+
using namespace std;
15+
16+
17+
18+
class Solution
19+
{
20+
public:
21+
int setBits(int N)
22+
{
23+
int count =0;
24+
while (N) {
25+
N &=(N-1);
26+
count ++;
27+
28+
}
29+
return count;
30+
}
31+
};
32+
33+
// { Driver Code Starts.
34+
int main()
35+
{
36+
int t;
37+
cin >> t;
38+
while (t--)
39+
{
40+
int N;
41+
cin >> N;
42+
43+
Solution ob;
44+
int cnt = ob.setBits(N);
45+
cout << cnt << endl;
46+
}
47+
return 0;
48+
}
49+
// } Driver Code Ends

0 commit comments

Comments
 (0)