-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBits.cpp
More file actions
87 lines (71 loc) · 1.72 KB
/
Bits.cpp
File metadata and controls
87 lines (71 loc) · 1.72 KB
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
/*
________________________________________
----------------------------------------
Author : Niharika Dutta
Code Link :
Time Complexity :
________________________________________
----------------------------------------
*/
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
#define ll long long
#define lli long long int
#define vi vector<int>
#define vll vector<ll>
#define pb push_back
#define mp make_pair
#define loop1(n) for (ll i = 0; i < (n); i++)
#define loop2(n) for (ll i = 1; i <= (n); i++)
#define test \
ll t; \
cin >> t; \
while (t--)
/*
_________________________________
A B AND OR
_________________________________
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
*/
int countSetBits(int n)
{
int count = 0;
while (n)
{
n = n & (n - 1);
count++;
}
return count;
}
int counting01(int num)
{
int zero = 0, one = 0;
while (num > 0)
{
if (num & 1)
one++;
else
zero++;
num = num >> 1;
}
return zero;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int num = 6;
int totalBits = (int)log2(num) + 1;
int oneCount1 = __builtin_popcount(num); // TC O(num)
// Brian Kernighan’s Algorithm: TC O(k)
int oneCount2 = countSetBits(num);
counting01(num); // TC O(log N)
cout << "Total Bits in its Binary Number : " << totalBits << endl
<< "Number of 1's : " << oneCount << endl;
return 0;
}