Thursday, April 9, 2015

Update Bits

Update Bits

Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j)   

Example
Given N = (10000000000)2, M = (10101)2, i = 2, j = 6
return N = (10001010100)2
Challenge
Minimum number of operations?

-------------------------- thinking -----------------------------------------
the codes below will return 0 instead of oxffffffff
             int k = 31;
             unsigned int test = (1 << (k+1))-1;
How ever the if we use (1<<32)-1 , we will get 0xffffffff !!!!!!!!!
------------------------ codes --------------------------------
class Solution {
public:
    /**
     *@param n, m: Two integer
     *@param i, j: Two bit positions
     *return: An integer
     */
    int updateBits(int n, int m, int i, int j) {
        // write your code here
        unsigned int new_m = m << i;
        unsigned mask;
        if (j == 31) {
            mask = 0xffffffff - ((1<<i)-1);
        } else {
            mask = ((1<<(j+1))-1) - ((1<<i)-1);
        }
        mask = ~mask;
        return (n & mask) | new_m;
    }
};

No comments:

Post a Comment