Skip to content

201. Bitwise AND of Numbers Range 👍

  • Time: $O(32) = O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int rangeBitwiseAnd(int m, int n) {
    int shiftBits = 0;

    while (m != n) {
      m >>= 1;
      n >>= 1;
      ++shiftBits;
    }

    return m << shiftBits;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int rangeBitwiseAnd(int m, int n) {
    int shiftBits = 0;

    while (m != n) {
      m >>= 1;
      n >>= 1;
      ++shiftBits;
    }

    return m << shiftBits;
  }
}
1
2
3
class Solution:
  def rangeBitwiseAnd(self, m: int, n: int) -> int:
    return self.rangeBitwiseAnd(m >> 1, n >> 1) << 1 if m < n else m