very simple solution in C++


  • 0
    E
    int rangeBitwiseAnd(int m, int n) {
        if (n == 0)
            return 0;
        int ans = 0;
        unsigned int mask = 0x80000000;
        while (!(mask & n))   //locate the highest bit of n
            mask = mask >> 1;
        while (mask) {
            if ((mask & m) == (mask & n))  //if the bits at this index in m and n are the same, put this bit in the answer.
                ans |= (mask & m);
            else                                       //if not, set the bits after this bit to zero (including this bit) and return.
                return ans;
            mask = mask >> 1;
        }
        return and;
    }
    

    very simple and relatively effective


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.