Conditional selection between x and y with bitwise operations
MediumUpdated: Sep 30, 2025
Problem
Given three 32-bit integers x, y, and b, return x if b is 1 and y if b is 0, using only mathematical or bit operations. You can assume b can only be 1 or 0.
Examples
Example 1
Input:
x = 42
y = 7
b = 1
Output:
42
Explanation:
Since b = 1 we must return x. mask = -b = -1 (all 1 bits). (x & mask) = x and (y & ~mask) = 0, so result = x.
Example 2
Input:
x = 42
y = 7
b = 0
Output:
7
Explanation:
Since b = 0 we must return y. mask = 0 so (x & mask) = 0 and (y & ~mask) = y.
Solution
Method 1 - Using bitwise masks
The core idea is to leverage bitwise operations to create masks based on the value of b, which will then be used to select either x or y.
Here’s the approach in a succinct form:
- If
bis1, we want to returnx. - If
bis0, we want to returny.
We can use bitwise operations to achieve this:
- Let’s create a mask based on the value of
b. - If
b = 1, the mask will be all1s. - If
b = 0, the mask will be all0s.
Mathematical Bitwise Solution
-
Compute
mask = -b:- If
b = 1,maskwill be all1s (which is0xFFFFFFFFfor 32-bit integers). - If
b = 0,maskwill be all0s (which is0x00000000for 32-bit integers).
- If
-
Use the mask to select
xory:result = (x & mask) | (y & ~mask)
Explanation
- When
bis1,maskbecomes0xFFFFFFFF, sox & maskyieldsx, andy & ~maskyields0. The bitwise OR of these results isx. - When
bis0,maskbecomes0x00000000, sox & maskyields0, andy & ~maskyieldsy. The bitwise OR of these results isy.
Code
Java
public class Solution {
public static int select(int x, int y, int b) {
// Compute masks based on the value of b
int mask = -b; // This will be all 1's if b is 1 and all 0's if b is 0
return (x & mask) | (y & ~mask);
}
public static void main(String[] args) {
int x = 42;
int y = 7;
int b1 = 1;
int b2 = 0;
System.out.println(select(x, y, b1)); // Output: 42
System.out.println(select(x, y, b2)); // Output: 7
}
}
Python
def select(x, y, b):
# Compute the mask based on the value of b
mask = -b # This will be all 1's if b is 1 and all 0's if b is 0
return (x & mask) | (y & ~mask)
# Example usage:
x = 42
y = 7
b1 = 1
b2 = 0
print(select(x, y, b1)) # Output: 42
print(select(x, y, b2)) # Output: 7
Complexity
- ⏰ Time complexity:
O(1)- This is because all operations (computing the mask, bitwise AND, bitwise NOT, bitwise OR) are constant-time operations.
- 🧺 Space complexity:
O(1)