[LintCode] Update Bits

class Solution {
    /**
     *@param n, m: Two integer
     *@param i, j: Two bit positions
     *return: An integer
     */
    public int updateBits(int n, int m, int i, int j) {
        // write your code here
        for(int k = i ; k <= j; k++) {
            n = n & ~(1 << k); // set kth bit in n to 0
            n = n | ((m & (1<<(k-i)))<<i); //set kth bit in n to m's kth bit
        }
        return n;
    }
}

n = n & ~(1 << k); 就是把n中的第k个bit设为0

n = n | ((m & (1<<(k-i)))<<i);

  1. m & (1<<(k-i)) 是从m的第一个bit开始扫描.因为已知j-i = size of (m)2
  2. ((m & (1<<(k-i)))<<i) 扫描后, 往左shift i位对准n上的i位.
  3. n = n | ((m & (1<<(k-i)))<<i) 把n的第i位到j位设为m的0~(j-i)位