LeetCode 201: Bitwise AND of Numbers Range Solution

Master LeetCode problem 201 (Bitwise AND of Numbers Range), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

201. Bitwise AND of Numbers Range

Problem Explanation

Explanation:

To find the bitwise AND of all numbers in the range [left, right], we need to analyze the binary representation of the left and right numbers. The idea is to find the common prefix of the binary representations of left and right. The bits that are different in the binary representations of left and right will eventually be zeroed out in the result.

  1. Identify the common prefix of the binary representations of left and right.
  2. Left-shift the common prefix by the number of bits that are different between left and right.

Time Complexity: O(log n), where n is the maximum of left and right. Space Complexity: O(1)

:

Solution Code

class Solution {
    public int rangeBitwiseAnd(int left, int right) {
        int count = 0;
        while (left < right) {
            left >>= 1;
            right >>= 1;
            count++;
        }
        return left << count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 201 (Bitwise AND of Numbers Range)?

This page provides optimized solutions for LeetCode problem 201 (Bitwise AND of Numbers Range) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 201 (Bitwise AND of Numbers Range)?

The time complexity for LeetCode 201 (Bitwise AND of Numbers Range) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 201 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 201 in Java, C++, or Python.

Back to LeetCode Solutions