-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind first set bit.cpp
133 lines (103 loc) · 2.43 KB
/
Find first set bit.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
//{ Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
/*
Find first set bit
Input:
1 18
Output:
2
Explanation:
TC: O(1) and SC: O(1)
log2(n & -n) + 1 and log2(n & ~(n - 1)) + 1 both works same.
log2(n & -n):
Here, n & -n will give the rightmost set bit of n.
-n is the 2’s complement of n. It is obtained by changing all the 0’s to 1 and 1’s to 0 and adding 1 to it.
18 = 10010
-18 = 01101 + 1 = 01110
10010 && 01110 = 00010
Answer = log2(00010) + 1 = log2(2) + 1 = 1 + 1 = 2
log2(n & ~(n - 1)):
Here, n & ~(n - 1) will give the rightmost set bit of n.
n - 1 will have all the bits same as n, except for the rightmost set bit of n and all the bits to the right of it.
18 = 10010
17 = 10001
~17 = 01110
10010 && 01110 = 00010
Answer = log2(00010) + 1 = log2(2) + 1 = 1 + 1 = 2
Note:
While there are specific cases where ~(n-1) and -n may produce the same result,
such as when n is a power of 2 or when n is a negative integer with all bits set to 1,
they are not generally equivalent. In most cases, these expressions will yield different values.
Alternative Approach 1:
TC: O(Log(N)) and SC: O(1)
Note: Right Shift Operator >>
a = 5; which is 101 in Binary Form.
Now, if “a is right-shifted by 2” i.e a >> 2 then a will become a = 1
0101 -> 01
unsigned int getFirstSetBit(int n)
{
int pos = 1;
while (n > 0)
{
// Checking if last bit is set
if (n & 1)
{
return pos;
}
// Increment position and right shift number by 1
n = n >> 1;
pos++;
}
return 0;
}
Alternative Approach 2:
TC: O(Log(N)) and SC: O(1)
unsigned int getFirstSetBit(int n)
{
int pos = 0;
while (n > 0)
{
if (n % 2 == 1)
{
return pos + 1;
}
n = n / 2;
pos++;
}
return 0;
}
Above Code Explanation:
18 = 10010
n = 18
n = 9 after n/2
9 = 1001
*/
class Solution
{
public:
// Function to find position of first set bit in the given number.
unsigned int getFirstSetBit(int n)
{
return log2(n & -n) + 1;
}
};
//{ Driver Code Starts.
// Driver code
int main()
{
int t;
cin >> t; // testcases
while (t--)
{
int n;
cin >> n; // input n
Solution ob;
printf("%u\n", ob.getFirstSetBit(n)); // function to get answer
}
return 0;
}
// } Driver Code Ends