Straightfoward C++ Solution


  • 0

    The idea is that, if n - m is greater than 2^n, then the nth bit of the result must be zero. Also, we need to check the two ends, if either of their nth bit is 0, the same happens to the result.

    int rangeBitwiseAnd(int m, int n) {
        int ans = m, mask = 1; 
        while( mask > 0 && ans ) {
            if( ( n-m >= mask ) || (m/mask)%2 == 0 || (n/mask)%2 == 0 )
                ans &= ~(mask);
            else break;
            mask <<= 1;
        }
        return ans;
    }

Log in to reply
 

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