Bitwise AND of Numbers Range - Complete Solution Guide
Bitwise AND of Numbers Range is LeetCode problem 201, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 <= 2 31 - 1
Detailed Explanation
The problem asks us to find the bitwise AND of all numbers within a given range [left, right] (inclusive). Bitwise AND operation compares each bit of the two numbers. If the bit is 1 in both numbers, the corresponding result bit is set to 1. Otherwise, the result bit is set to 0.
Solution Approach
The solution leverages the observation that the bitwise AND of a range of numbers will only have '1's in the most significant bits that are common to all numbers in the range. The core idea is to repeatedly right-shift both 'left' and 'right' until they become equal. This effectively removes the differing least significant bits, isolating the common prefix. The number of right shifts is then used to shift the common prefix back to its original position, yielding the final result.
Step-by-Step Algorithm
- Step 1: Initialize a 'shift' counter to 0. This counter tracks how many times 'left' and 'right' are right-shifted.
- Step 2: Enter a 'while' loop that continues as long as 'left' is strictly less than 'right'.
- Step 3: Inside the loop, right-shift both 'left' and 'right' by 1 bit (i.e., divide by 2 and discard the remainder). This removes the least significant bit.
- Step 4: Increment the 'shift' counter by 1 for each right-shift operation.
- Step 5: After the loop terminates (when 'left' equals 'right'), left-shift 'left' by 'shift' bits (i.e., multiply 'left' by 2 raised to the power of 'shift'). This restores the common prefix to its original place value.
- Step 6: Return the final value of 'left'.
Key Insights
- Insight 1: The bitwise AND of a range of numbers will have common prefix bits. Once the bits start to differ between the left and right bounds, all bits to the right will become zero due to the inclusion of numbers with differing bits.
- Insight 2: Repeatedly right-shifting both 'left' and 'right' until they become equal effectively identifies the common prefix. The number of shifts represents the power of 2 that was factored out.
- Insight 3: The result is the common prefix, shifted back by the same number of positions to restore the original scale.
Complexity Analysis
Time Complexity: O(log(n))
Space Complexity: O(1)
Topics
This problem involves: Bit Manipulation.
Companies
Asked at: Google.