Isolate the rightmost 1-bit
EasyUpdated: Sep 30, 2025
Problem
Given an integer x, isolate (keep) only the rightmost set bit (1) and clear all other bits. If x is 0, the result is 0.
Examples
Examples 1
Input: x = 0b01011010
Output: 0b00000010
Explanation: only the rightmost 1-bit is preserved.
Examples 2
Input: x = 0
Output: 0
Solution
Method 1 - Bit trick (x & -x)
Intuition
-x in two's complement is equivalent to ~x + 1. The operation x & -x clears all bits except the rightmost 1. Intuitively, adding 1 to ~x propagates a carry to the first 1-bit from the right, which makes -x share only that bit with x when AND-ed.
Approach
- If
x == 0, return0. - Compute
ans = x & -xand returnans.
Edge cases:
- Negative numbers: the expression works with two's complement signed integers (the rightmost set bit of the bit-pattern is isolated).
Code
C++
class Solution {
public:
long isolateRightmost(long x) {
return x & -x;
}
};
Go
package main
// isolateRightmost returns a value with only the rightmost set bit of x preserved.
func isolateRightmost(x int64) int64 {
return x & -x
}
Java
class Solution {
public long isolateRightmost(long x) {
return x & -x;
}
}
Python
class Solution:
def isolate_rightmost(self, x: int) -> int:
return x & -x
Complexity
- ⏰ Time complexity:
O(1), computingx & -xtakes constant time. - 🧺 Space complexity:
O(1), only a constant number of variables used.
Method 2 - Bit scan (find position then mask)
Intuition
Scan bits from least-significant to most-significant to find the index of the first 1. Then return 1 << pos (or the equivalent mask) to isolate that bit.
Approach
- If
x == 0, return0. - Initialize
pos = 0. - While
(x & 1) == 0, shiftx >>= 1and incrementpos. - Return
1 << pos(or the mask with only that bit set).
Code
C++
class Solution {
public:
long isolateRightmostScan(long x) {
if (x == 0) return 0;
int pos = 0;
while ((x & 1) == 0) {
x >>= 1;
++pos;
}
return 1L << pos;
}
};
Go
package main
func isolateRightmostScan(x int64) int64 {
if x == 0 {
return 0
}
pos := int64(0)
for (x & 1) == 0 {
x >>= 1
pos++
}
return 1 << pos
}
Java
class Solution {
public long isolateRightmostScan(long x) {
if (x == 0) return 0;
int pos = 0;
while ((x & 1) == 0) {
x >>= 1;
++pos;
}
return 1L << pos;
}
}
Python
class Solution:
def isolate_rightmost_scan(self, x: int) -> int:
if x == 0:
return 0
pos = 0
while (x & 1) == 0:
x >>= 1
pos += 1
return 1 << pos
Complexity
- ⏰ Time complexity:
O(w)wherewis the word size (number of bits); in practice this is O(1) for fixed-width integers but linear in the bit-length if considered variable. - 🧺 Space complexity:
O(1).