Home Practice Programming Insert M into N such that M starts at bit j and...

Insert M into N such that M starts at bit j and ends at bit i

Given two 32-bit numbers, Nand M, and two-bit positions, i and j. Write a method to insert Minto N such that M starts at bit j and ends at bit i. Assume that the bits i to j in N have enough space to fit all of M. That is, if M = 10011, you can assume that there are at least 5 bits between j and i. You would not, for
example, have j = 3 and i = 2 because M could not fully fit between bit 3 and bit 2.

Example1: m = 1082 = 100001110102
          n = 19   = 100112
          i = 2 and j = 6
          result = 1102 = 100010011102
                   1 0 0 0 0 1 1 1 0 1 0
                           1 0 0 1 1
                   ------------------------
                   1 0 0 0 1 0 0 1 1 1 0

Example2: m = 734 = 10110111102
          n = 9 = 10012
          i = 2 and j = 5
          result = 742
                   1 0 1 1 0 1 1 1 1 0
                           1 0 0 1 
                   ---------------------
                   1 0 1 1 1 0 0 1 1 0

Algorithm

To achieve this solution, we have to follow the following steps:

Clear Bit in range i to j

Step 1: Clear the bits in the range i to j (inclusive).

Step 2: Shift m left by i bits. (m = m<<i)

Shift M left by i bits

Step 3: XOR n and m to insert m into n in range i to j.

insert m in n using XOR

Implementation of the above algorithm in CPP

#include <bits/stdc++.h>
using namespace std;

int update_range(int n, int m, int i, int j){
	int mask = (1<<(j+1))-1;

	mask = mask^((1<<(i+1))-1);
	mask = ~mask;
	n = n&mask;

	return n|(m<<i);
}

int main(){
	
	int n, m, i, j;
	cin>>n>>m>>i>>j;
	int result = update_range(n,m,i,j);
	cout<<result<<endl;

	return 0;
}

Output

742    (for n = 734, m = 9, i = 2, j = 5)

Did, we miss something, or do you want to add some other key points?🤔
Please comment.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Subscribe to our weekly newsletter

Join our community of 1000+ developers and stay updated with the fast moving world of computer science

We promsie, we won't spam
Even we hate spam as much as you hate them

Books recommendation for interview preparation