AlgoMaster Logo

Bitwise AND of Numbers Range

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Bitwise AND

Intuition:

The simplest method is to calculate the bitwise AND for every number in the range [m, n]. This approach guarantees that we consider every number but can result in unnecessary computations. The key observation in this approach is that any bit position that becomes zero remains zero for all subsequent numbers in the range.

Steps:

  1. Initialize a result variable with the value of m.
  2. Iterate through numbers from m + 1 to n.
  3. Perform a bitwise AND operation between the result and the current number.
  4. Return the result.

This approach iterates over the range and progressively accumulates the AND result. However, this method can be quite inefficient for large ranges.

Code:

2. Bit Manipulation - Common Prefix

Intuition:

In any range of numbers where the upper and lower bounds differ, certain trailing bits in the binary representation will vary. We can track how much both numbers need to be right-shifted until they match, effectively finding a common prefix. This prefix will form the result since any bits that remain the same between m and n should dominate the final AND operation.

Algorithm:

  1. Initialize a shift counter to 0.
  2. While m is not equal to n, right shift both m and n.
  3. Increment the shift counter each time you right shift.
  4. The result is the common prefix left-shifted back to its original position.

This approach efficiently finds the common range prefix, highlighting where numbers differ.

Code: