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
|
|
|
|
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)