JAVA code with pictures


  • 0
    A
    public int rangeBitwiseAnd(int m, int n) {
        int shiftCount = 0;
        while(m != n) {
            n = n >> 1;
            m = m >> 1;
            shiftCount++;
        }
        return n << shiftCount;
    }

  • 0
    A

    If m != n, then there are zero or more numbers in between them. And every consecutive number differs by the rightmost bit. The right-most zero will turn that bit into zero in the final result, hence we can shfit through that bit till m == n.
    alt text
    alt text
    alt text


Log in to reply
 

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