VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-position-of-the-only-set-bit/

⇱ Position of the only set bit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Position of the only set bit

Last Updated : 22 Apr, 2026

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 between n and n-1 results in 0 if n is a power of 2, as the single set bit cancels out. 

Using Left Shift Operator - O(log(n)) time and O(1) space

The idea is to use a loop where we left shift the number 1 and perform a bitwise AND operation with n. 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) :

  • Check (n == 0 => false) OR ((n & (n - 1)) != 0)
    (n & (n - 1)) = (2 & 1) = 0 => (0 != 0) = false
    So (false OR false = false), hence continue.
  • Initialize pos = 1, val = 1 (binary: 01)
  • (val & n) = (1 & 2) = 0 so condition true, enter loop
    val = val << 1 = 1 << 1 = 2 (binary: 10), pos = 2
  • (val & n) = (2 & 2) = 2 so condition false, exit loop

Final answer is: pos = 2


Output
2

Using Right Shift Operator - O(log(n)) time and O(1) space

The idea is to right shift the number n until the rightmost bit becomes 1. The number of shifts required to reach this point gives the position of the set bit.

Dry run for n = 2 (binary = 10) :

  • Check (n == 0 => false) OR ((n & (n - 1)) != 0)
    (n & (n - 1)) = (2 & 1) = 0 => (0 != 0) = false
    So (false OR false = false), hence continue.
  • Initialize pos = 1
  • (n & 1) = (2 & 1) = 0 so condition is true, enter loop
    n = n >> 1 = 2 >> 1 = 1 (binary: 01), pos = 2
  • (n & 1) = (1 & 1) = 1 so condition is false, exit loop

Final answer is: pos = 2


Output
2

Using Log Operator - O(log n) time and O(1) space

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 of n and adding 1 (since the position is 1-based).


Output
2

Related Article:

Comment
Article Tags: