Skip to content

Commit 05ef239

Browse files
committed
Find position of set bit using C++
1 parent 2458138 commit 05ef239

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
2+
/*
3+
Given a number N having only one ‘1’ and all other ’0’s in its binary representation, find position of the only set bit. If there are 0 or more than 1 set bit the answer should be -1. Position of set bit '1' should be counted starting with 1 from LSB side in binary representation of the number.
4+
5+
Example 1:
6+
7+
Input:
8+
N = 2
9+
Output:
10+
2
11+
Explanation:
12+
2 is represented as "10" in Binary.
13+
As we see there's only one set bit
14+
and it's in Position 2 and thus the
15+
Output 2.*/
16+
#include <bits/stdc++.h>
17+
using namespace std;
18+
19+
20+
class Solution {
21+
public:
22+
23+
int isPowerOfTwo(unsigned N)
24+
{
25+
return N && (!(N & (N - 1)));
26+
}
27+
int findPosition(int N) {
28+
// code here
29+
if (!isPowerOfTwo(N))
30+
return -1;
31+
32+
unsigned i = 1, pos = 1;
33+
34+
35+
while (!(i & N)) {
36+
37+
i = i << 1;
38+
39+
// increment position
40+
++pos;
41+
}
42+
43+
return pos;
44+
45+
}
46+
};
47+
48+
// { Driver Code Starts.
49+
int main() {
50+
int t;
51+
cin >> t;
52+
while (t--) {
53+
int N;
54+
55+
cin>>N;
56+
57+
Solution ob;
58+
cout << ob.findPosition(N) << endl;
59+
}
60+
return 0;
61+
} // } Driver Code Ends

0 commit comments

Comments
 (0)