8ms Java solution, without loop


  • 0
    R

    The idea behind this solution is that we need to find the bit positions which can change and use a bitmask based on them, since those bits will be 0. (link)

    public int rangeBitwiseAnd(int m, int n) {
            if( m == n ) return m;
            int diff = n - m - 1;
            diff |= diff >>> 1;
            diff |= diff >>> 2;
            diff |= diff >>> 4;
            diff |= diff >>> 8;
            diff |= diff >>> 16;
            return m & n & ~diff;
        }
    

  • 0
    M

    @rideg This link seems to be broken


  • 0
    R

    Thanks, now it is fixed.


Log in to reply
 

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