02. Copy Set Bits in Range
My approach
Example
Given:
- x = 1090 (10001000010)
- y = 1211 (10010111011)
- l = 2
- r = 6
Steps:
1. Since l = 2 and r = 6 are inclusive in the range,
maskLen = 5.
2. Calculate the mask:
- Initialize mask as 1 shifted left by maskLen: mask = 1 << 5 = 32 (100000)
- Subtract 1 from mask: mask = mask - 1 = 31 (011111)
(We obtain a mask with the required length of 5 ones)
- Shift the mask towards the left boundary by (l - 1): mask = mask << (l - 1) = (0111110)
(This is our required mask)
3. Filter out y value:
y' = y & mask = (10010111011) & (0111110) = (0111010)
4. Copy x or y:
Result = x | y' = (10001000010) | (0111010) = 1146 (10001111010)Time and Auxiliary Space Complexity
Code (C++)
Contribution and Support
Last updated