LeetCode Solutions

201. Bitwise AND of Numbers Range

Time: $O(32) = O(1)$

Space: $O(1)$

			

class Solution {
 public:
  int rangeBitwiseAnd(int m, int n) {
    int shiftBits = 0;

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

    return m << shiftBits;
  }
};
			

class Solution {
  public int rangeBitwiseAnd(int m, int n) {
    int shiftBits = 0;

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

    return m << shiftBits;
  }
}
			

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