179. 更新二进制位

179. 更新二进制位 

 

给出两个32位的整数N和M,以及两个二进制位的位置i和j。写一个方法来使得N中的第i到j位等于M(M会是N中从第i为开始到第j位的子串)

 注意事项

In the function, the numbers N and M will given in decimal, you should also return a decimal number.

说明

You can assume that the bits j through i 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.

样例

给出N = (10000000000)2,M = (10101)2, i = 2, j = 6

返回 N = (10001010100)2

int UpdateBits::updateBits(int n, int m, int i, int j) {
    // write your code here
    /*
     *  解题思路:如果j<31,即j不在最高位上。可以把i到j位清为0,可以((1<<(j+1))-(1<<i))得到i到j之间全是1的数,再取反,得到i到j之间全是0的数。
     *  如果j=31,(1<<(j+1))即(1<<32),相当于1<<1 不可行。可以直接(1<<i)-1 得到i到j之间全是0,其他地方是1的数。
     *  上面得到的数成为掩码
     *  (m<<i)+(n&mask) 可以得到最终解。
     * */
    Print2(n);
    Print2(m);
    int mask = 0;
    if (j < 31) {
        mask = ~((1 << (j + 1)) - (1 << i));
        cout << "j+1->>>" << endl;
        Print2(1 << (j + 1));
        cout << "(1 << i)" << endl;
        Print2(1 << i);

        Print2((1 << (j + 1)) - (1 << i));

    } else {
        mask = (1 << i) - 1;
    }


    Print2(mask);
    n = (m << i) + (n & mask);
    Print2(n);
    return n;
}

void UpdateBits::Print2(int num) {
    cout << bitset<sizeof(int) * 8>(num) << endl;
}

  

原文地址:https://www.cnblogs.com/kanekiken/p/7989434.html