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