Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

I. Problem description

Given two integer numbers N and M, and I and j representing the bit position (I <= j, counting from bit 0).

Write a method to insert the binary digits corresponding to M into the I ~ j region corresponding to the binary digits corresponding to N, and to complete the deficiency with 0. The specific insertion process is shown in the figure.

For example, if M = 10011, the region from I to j can contain at least 5 bits.

Title link: insert.

Two, the title requirements

The sample

Input: N = 1024(10000000000), M = 19(10011), I = 2, j = 6 Output: N = 1100(10001001100)Copy the code

inspection

2. It is recommended to take 15 to 30 minutesCopy the code

Third, problem analysis

14. If you do not know about bit operation, you can read the article in detail.

Day 45: Bit operation.

Just got this problem, I want to judge a one digit, when I started to do it found too much trouble, and the advantages of bit operation did not play out. Open the comment section of this question and some people (including me) are already beginning to mess up.

Look at the solution of the problem found a big clever approach, divided into three steps to solve:

1. Set N binary I to j to 0 in xOR calculation. Because 1<<k must be a subset of N, same, xor is 0 2. Move M to the left by I positions 3.N+M, return the resultCopy the code

Four, coding implementation

class Solution {
public:
    int insertBits(int N, int M, int i, int j) {
        int k;
        for(k=i; k<=j; k++)// set N binary I ~j to 0
        {
            if(N&(1<<k))
            {
                N=N^(1<<k);// Xor calculation
            }
        }
        M=M<<i;// Move M to the left by I
        return N+M;//N+M}};Copy the code

V. Test results