Given two integers left and right that represent the range [left, right], return the bitwise AND of all numbers in this range, inclusive.
Input: left = 5, right = 7
Output: 4
Input: left = 0, right = 0
Output: 0
Input: left = 1, right = 2147483647
Output: 0
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.
m.m + 1 to n.This approach iterates over the range and progressively accumulates the AND result. However, this method can be quite inefficient for large ranges.
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.
This approach efficiently finds the common range prefix, highlighting where numbers differ.