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.
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
b
is1
, we want to returnx
. - If
b
is0
, 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 all1
s. - If
b = 0
, the mask will be all0
s.
Mathematical Bitwise Solution
Compute
mask = -b
:- If
b = 1
,mask
will be all1
s (which is0xFFFFFFFF
for 32-bit integers). - If
b = 0
,mask
will be all0
s (which is0x00000000
for 32-bit integers).
- If
Use the mask to select
x
ory
:result = (x & mask) | (y & ~mask)
Explanation
- When
b
is1
,mask
becomes0xFFFFFFFF
, sox & mask
yieldsx
, andy & ~mask
yields0
. The bitwise OR of these results isx
. - When
b
is0
,mask
becomes0x00000000
, sox & mask
yields0
, andy & ~mask
yieldsy
. 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)