Simple Java solution, easy to understand


  • 0
    L

    10ms. Not fast enough, but is easy to understand.

    For the lowest bit to be "1", it has to be both m and n have their bits as "1", and also "m == n". If m < n, m + 1, which is <= n, will give a "0" on this bit. In order to always only worry about the lowest bit, we keep on shifting m and n to the right.

    public int rangeBitwiseAnd(int m, int n) {
            int result = 0;
            
            for (int i = 0; i < 31; i++) {
                if ((m & 1) == 1 && (n & 1) == 1 && n == m) {
                    result |= 1 << i;
                }
                m >>= 1;
                n >>= 1;
            }
            return result;
    }

Log in to reply
 

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