Given an integer x, set (turn on) the rightmost 0 bit (least-significant zero) and return the resulting value. If there is no 0 bit in the relevant word width, the value remains unchanged.
Input: x =0b10111100=> Output:0b10111101Input: x =0b01110111=> Output:0b01111111Input: x =0b00000001=> Output:0b00000011Input: x =0b11111111=> Output:0b11111111(no zero to set)
Adding 1 to x fills the first (rightmost) zero bit and zeroes all lower bits. OR-ing x with x+1 therefore sets that zero without clearing any other set bits. If x has no zero in the considered width, x+1 may overflow and the OR leaves x unchanged.
Find the index of the rightmost zero and set it explicitly with a mask. This is explicit and safe across languages where overflow behavior is a concern.
classSolution {
publicintturnOnRightmostZeroScan(int x, int width) {
for (int i = 0; i < width; ++i) {
if (((x >> i) & 1) == 0) return x | (1 << i);
}
return x;
}
}
1
2
3
4
5
6
classSolution:
defturn_on_rightmost_zero_scan(self, x: int, width: int =32) -> int:
for i in range(width):
if ((x >> i) &1) ==0:
return x | (1<< i)
return x
Method 1 is constant-time and preferred. Method 2 is safer in environments where overflow or undefined behavior for x+1 could be an issue, or when you explicitly want to control word width.