</>

201. Bitwise AND of Numbers Range

Medium
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Bit Manipulation
Time
—
Space
—

Standard Solution (C++)

SummaryGiven two non-negative integers `left` and `right`, find the bitwise AND of every integer in the inclusive range `[left, right]`.

Approach
  • Any bit that differs across the range will be flipped to 0 by the AND, so only the common prefix of left and right in binary survives.
  • Repeatedly right-shift both values until they are equal; each shift discards one bit where they diverge, and we count the shifts.
  • Left-shifting the common prefix back by the number of discarded bits produces the answer.
  • This works in at most 32 iterations for 32-bit integers, making it effectively O(1).
#include <cstdint>
using namespace std;

class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        // Find the common high-order prefix shared by left and right.
        // Every bit where the two numbers differ will be 0 in the AND of
        // the full range, so only the common prefix contributes.
        int shift = 0;
        while (left != right) {
            left  >>= 1;
            right >>= 1;
            ++shift;
        }
        // Restore the prefix to its original bit position.
        return left << shift;
    }
};
Time O(1) — at most 32 iterations for a 32-bit integer Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int rangeBitwiseAnd(int left, int right) {
        // 101 (left)
        // 111 (right)
        // 100 (find the common prefix)

        unsigned short shift=0;
        while(left<right){
            left>>=1;
            right>>=1;
            ++shift;
        }

        return left<<shift;
    }
};

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern