![]() |
VOOZH | about |
Given a number n containing only 1 set bit in its binary representation, the task is to find the position of the only set bit. If there are 0 or more than 1 set bits, then return -1.
Note: Position of set bit '1' should be counted starting with 1 from the LSB side in the binary representation of the number.
Examples:-
Input: n = 2
Output: 2
Explanation: Binary representation of 2 is 10. We can observe that the only set bit is at position 2 from LSB.Input: n = 5
Output: -1
Explanation: Binary representation of 5 is 101. There are 2 set bits, so return -1.
Condition for numbers having only 1 set bit:
Numbers having only one set bit will be a power of 2 number ( example, 20 = 1, 21 = 10, 22 = 100, 23 = 1000).
When you subtract 1 from such a number, all bits after the set bit (including the set bit itself) flip (e.g., 4 =
100, 3 =011). Performing a bitwise AND betweennandn-1results in0ifnis a power of 2, as the single set bit cancels out.
Table of Content
The idea is to use a loop where we left shift the number
1and perform a bitwise AND operation withn. If the result is non-zero, the position of the set bit is determined by the number of shifts performed.
Dry run for n = 2 (binary = 10) :
Final answer is: pos = 2
2
The idea is to right shift the number
nuntil the rightmost bit becomes1. The number of shifts required to reach this point gives the position of the set bit.
Dry run for n = 2 (binary = 10) :
Final answer is: pos = 2
2
The idea is to use the mathematical property that the position of the only set bit in a number
n(which is a power of 2) can be found by taking the base-2 logarithm ofnand adding 1 (since the position is 1-based).
2
Related Article: