Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding
Ninjas X Naukri.com

Last Updated: 21 Feb, 2021

Easy

```
X = 1536 and Y = 7, A = 1 and B = 5,
X is base 2 = 11000000000, Y in base 2 = 0111
First, we clear all the bits of X from index 1 to index 5 then wrote Y in X starting from A.
After inserting Y in X starting from position result will be 11000001110
```

```
The first line of input contains an integer 'T’ denoting the number of test cases to run. Then the test case follows.
The first and the only line of each test case contain four single space-separated integers ‘X’, ‘Y’, ‘A’, and ‘B’ denoting the integers and the starting and the ending positions for insertion, respectively.
```

```
For each test case print the number 'X' after inserting the 'Y' from A’th to B’th position.
Output for each test case is printed in a separate line.
```

```
You don’t need to print anything. It has already been taken care of. Just implement the given function.
```

```
1 <= T <= 5000
1 <= X,Y <= 2^31
0 <= A <= B < 32
‘X’, ‘Y’, ‘A’, ‘B’ are two given integers and starting bit positions and ending bit position to insert respectively.
It is guaranteed that the position from ‘A’ to ‘B’ is enough to insert Y.
Time Limit : 1 sec
```

The key observation here is that we can set all the bits in X to 0 from A’th bit to B’th bit using some bitwise operations. Then we finally shift Y by A bits and take the bitwise or with X.

The algorithm will be-

- Create a MASK with the first B - A + 1 bits set.
- Shift MASK by A bits to left.
- Negate the MASK and take bitwise and with X to clear all set bits of X from B to A.
- Shift Y by A bits and take its bitwise or with X. We finally return X.

Similar problems

Detect Odd

Moderate

Posted: 15 Apr, 2022

Detect Odd

Moderate

Posted: 15 Apr, 2022

Detect Odd

Moderate

Posted: 15 Apr, 2022

Detect Odd

Moderate

Posted: 15 Apr, 2022

Ninja And The Clan

Moderate

Posted: 17 Apr, 2022

Check whether K-th bit is set or not

Easy

Posted: 20 May, 2022

Check whether K-th bit is set or not

Easy

Posted: 20 May, 2022

Check whether K-th bit is set or not

Easy

Posted: 20 May, 2022

Check whether K-th bit is set or not

Easy

Posted: 20 May, 2022

Check whether K-th bit is set or not

Easy

Posted: 20 May, 2022

Maximum Element

Moderate

Posted: 21 Jul, 2022

XOR DARE

Moderate

Posted: 3 Sep, 2022