201. Bitwise AND of Numbers Range LeetCode Solution

In this guide, you will get 201. Bitwise AND of Numbers Range LeetCode Solution with the best time and space complexity. The solution to Bitwise AND of Numbers Range problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Bitwise AND of Numbers Range solution in C++
  4. Bitwise AND of Numbers Range solution in Java
  5. Bitwise AND of Numbers Range solution in Python
  6. Additional Resources
201. Bitwise AND of Numbers Range LeetCode Solution image

Problem Statement of Bitwise AND of Numbers Range

Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.

Example 1:

Input: left = 5, right = 7
Output: 4

Example 2:

Input: left = 0, right = 0
Output: 0

Example 3:

Input: left = 1, right = 2147483647
Output: 0

Constraints:

0 <= left <= right <= 231 – 1

Complexity Analysis

  • Time Complexity: O(32) = O(1)
  • Space Complexity: O(1)

201. Bitwise AND of Numbers Range LeetCode Solution in C++

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

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

    return m << shiftBits;
  }
};
/* code provided by PROGIEZ */

201. Bitwise AND of Numbers Range LeetCode Solution in Java

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

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

    return m << shiftBits;
  }
}
// code provided by PROGIEZ

201. Bitwise AND of Numbers Range LeetCode Solution in Python

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

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.