5.1 Insertion

We need a mask for this problem which helps us to clear the bits we need to insert.
The left part of 1s can shift left for j+1 bits. For right part, we can get it by set the initial value of right as INT_MAX then shift it 31 - i bits;

    int updateBits(int n, int m, int i, int j) {
        // write your code here
        int left = ~0 << (j+1);//all 1s left shift by j+1 bits;
        if(j >= 31 ) left = 0;
        int right = INT_MAX >> (31-i);//set the initial value of right = INT_Max we can get 1 at last;
        return ((left | right) & n) | (m << i);
    }

你可能感兴趣的:(BitMani)