Three different solutions in C, very terse and clean


  • 3
    int rangeBitwiseAnd(int m, int n)
    {
        int count = 0;
        while(m != n) //until the left identical bits, all the right will be cancelled by increments from m to n;;
        {
            m >>= 1;
            n >>= 1;
            count++;
        }
        return m << count;
    }
    

    //AC - get the left common part;
    int rangeBitwiseAnd1(int m, int n)
    {
        int r = INT_MAX;
        while((m&r) != (n&r)) r <<= 1;
        return n&r;
    }
    

    int rangeBitwiseAnd(int m, int n)
    {
        while(m < n) n &= n-1; //remove the right bit-1 until equal to or less than m;
        return n;
    }

Log in to reply
 

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