Insert Bits

Given two 32-bit integers N and M and two bit positions i and j, insert M into N so that M starts at bit j and ends at bit i. Pattern focus: Set/Clear kth Bit. Clear the target range in N first, then place M into that cleared slot.

Input Format

N = base integer, M = integer to insert, i and j = bit positions

Output Format

resulting integer after insertion

Constraints

  • 1 <= input size <= 10^5
  • -10^9 <= numeric values <= 10^9
  • N, M, i, j must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

N = 1024
M = 19
i = 2
j = 6

Output:

1100

Explanation:

Insert 10011 into 10000000000 from bit 2 to 6.

Example 2:

Input:

N = 0
M = 15
i = 0
j = 3

Output:

15

Explanation:

Putting 1111 into the lowest four bits gives 15.

Loading...
Insert Bits - Bit Manipulation DSA Problem