80ms C++ solution


  • 0
    H
    int rangeBitwiseAnd(int m, int n) {
        if (0 == m) return 0;
        if (m == n) return n;
        
        // n       : x...x 1 0 0 0
        // n-1     : x...x 0 1 1 1
        // ...     : x...x 0 . . .
        // n-2^3   : x...x 0 0 0 0
        // n&n-1   : x...x 0 0 0 0
        // n&n-2^3 : x...x 0 0 0 0
    
        int diff = n - m;
        
        int base = 1, offset = 0;
        while (++offset < 32) {
            if (0 != (n & base)) {
                diff -= base;
                if (diff <= 0) break;
            }
            base <<= 1; // ... 1 ...
        }
        // clear 'the last offset' bits
        int v = ((n >> offset) << offset);
        return v;
    }

  • 0
    H

    After view some other sharing, found my solution could be this way ...

    int rangeBitwiseAnd(int m, int n) {
        while (m < n) {
            n = n & (n-1);
        }
        return n;
    }

  • 1
    H

    After view some other sharing, found my solution could be this way ...

    int rangeBitwiseAnd(int m, int n) {
        while (m < n) {
            n = n & (n-1);
        }
        return n;
    }

Log in to reply
 

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