Bitwise AND of Numbers Range

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.

  • Time: O(n)
  • Space: O(1)
public int rangeBitwiseAnd(int m, int n) {
    int mask = Integer.MAX_VALUE;
    while ((m & mask) != (n & mask)) {
        mask <<= 1;
    }
    return m & n;
}

results matching ""

    No results matching ""