Problem Statement

Given an integer n:

Return the position of the only set bit (1) in its binary representation.

Position starts from 1 at the Least Significant Bit (LSB).

If:

  • n has no set bit (0)

  • OR has more than one set bit

then return:

-1

Understanding the Concept

A number has exactly one set bit only if it is a power of 2.

Examples:

NumberBinaryOne Set Bit?
10001Yes
20010Yes
40100Yes
81000Yes
50101No
101010No

Important Bit Trick

A number has exactly one set bit if:

Java
n & (n - 1) == 0

Why?

Because powers of 2 look like:

Code
1000
0100
0010

Subtracting 1 flips all lower bits:

Code
1000 -> 0111

AND operation becomes:

Code
1000 & 0111 = 0000

Algorithm

Step 1

Check:

  • n == 0

  • OR (n & (n - 1)) != 0

If true → return -1.

Step 2

Find position of the set bit.

Keep shifting right until bit becomes 1.

Dry Run

Example 1

Input:

Code
n = 2

Binary:

Code
10

Only one set bit exists.

Counting from right:

PositionBit
10
21

Answer:

Code
2

Example 2

Input:

Code
n = 5

Binary:

Code
101

Two set bits exist.

Answer:

Code
-1

Java Solution

Java
class Solution {
    
    public int findPosition(int n) {
        
        // Check if n has exactly one set bit
        if (n == 0 || (n & (n - 1)) != 0) {
            return -1;
        }
        
        int position = 1;
        
        // Find position of set bit
        while ((n & 1) == 0) {
            n = n >> 1;
            position++;
        }
        
        return position;
    }
}

Complexity Analysis

Time Complexity

Code
O(log n)

Because we may shift bits up to the number of bits in n.

Space Complexity

Code
O(1)

No extra space used.

Alternative Mathematical Insight

If n is a power of 2:

Code
Position = log2(n) + 1

Example:

Code
n = 8
log2(8) = 3
Position = 4

But using bit manipulation is preferred in interviews.

Key Interview Concepts

Power of Two Check

Code
n & (n - 1) = 0

This is one of the most important bit manipulation tricks.

Edge Cases

Case 1

Code
n = 0

Output:

Code
-1

No set bits.

Case 2

Code
n = 1

Binary:

Code
1

Set bit at position:

Code
1

Final Takeaway

To solve this efficiently:

  • Check whether the number has exactly one set bit.

  • Count the bit position using right shift.

Main trick:

Code
n & (n - 1)

This makes the solution elegant and interview-friendly.