Find position of the only set bit
Pattern: Bits basics
First check that n has exactly one set bit (n > 0 and n & (n - 1) == 0). Then shift right until that bit reaches the end, counting positions from 1.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given a whole number n, if it has exactly one set bit, return that bit's position counting from 1 at the right.
Otherwise (no set bit, or more than one) return -1. For example, 2 (10) gives 2, 1 gives 1, 5 (101) gives -1, and
0 gives -1.
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
findPosition and the -1 rule are this guide's own.
Think first
- How do you check "exactly one set bit" in O(1)?
- How do you find where that bit is?
- Is the position counted from 0 or 1?
Hints
Brute force, and why it fails
Check each of the 32 bits and count the ones and the position of the last one: O(32). The test plus shifting is the same order, and stops early.
The key insight
"Exactly one set bit" means a power of two, and the position of that bit is its exponent plus one.
Dry run
| pos | 1 |
|---|
n = 2, which is 10 in binary. It is positive and 2 & 1 = 0, so it has exactly one set bit.
The plan
if n <= 0 or (n & (n - 1)) != 0: return -1
pos = 1
while (n & 1) == 0: n = n >> 1; pos = pos + 1
return pos
Complexity
- Time
O(log n)- Space
O(1)
At most 31 shifts.
Edge cases
n = 0: -1.n = 1: 1.- Large powers such as
2^30: 31.
I've built my logic, show the code
Java
class Solution {
public int findPosition(int n) {
if (n <= 0 || (n & (n - 1)) != 0) return -1; // zero set bits, or more than one
int pos = 1;
while ((n & 1) == 0) { n >>= 1; pos++; } // shift until the set bit reaches the end
return pos;
}
}C++
class Solution {
public:
int findPosition(int n) {
if (n <= 0 || (n & (n - 1)) != 0) return -1; // zero set bits, or more than one
int pos = 1;
while ((n & 1) == 0) { n >>= 1; pos++; } // shift until the set bit reaches the end
return pos;
}
};Python
class Solution:
def findPosition(self, n: int) -> int:
if n <= 0 or n & (n - 1):
return -1 # zero set bits, or more than one
pos = 1
while n & 1 == 0: # shift until the set bit reaches the end
n >>= 1
pos += 1
return posCommon mistakes
- Counting positions from 0.
- Shifting until
n == 0, which goes one step too far. - Skipping the "exactly one bit" check.