Leetcode 201: Bitwise AND of Numbers Range

grid47
grid47
Exploring patterns and algorithms
Oct 17, 2024 5 min read

A series of overlapping circles, each representing a number, with a soft intersection of glowing bits in the middle.
Solution to LeetCode 201: Bitwise AND of Numbers Range Problem

Given two integers, left and right, representing a range [left, right], you need to calculate the bitwise AND of all numbers within that range, inclusive. The bitwise AND operation takes two numbers and returns a number where each bit is set to 1 if the corresponding bits of both numbers are also 1.
Problem
Approach
Steps
Complexity
Input: The input consists of two integers: left and right, representing the range [left, right].
Example: left = 10, right = 12
Constraints:
• 0 <= left <= right <= 231 - 1
Output: Return the result of the bitwise AND operation of all numbers between left and right, inclusive.
Example: Output: 8
Constraints:
• The output should be a single integer representing the result of the bitwise AND.
Goal: The goal is to efficiently calculate the bitwise AND of all numbers in the range [left, right].
Steps:
• Shift the left and right integers to the right until they become equal. Each time they are not equal, shift both numbers to the right by 1 bit.
• Count how many shifts were needed. The final result will be the right-shifted value of either left or right shifted back by the counted number of shifts.
Goal: The range of the integers is from 0 to 231 - 1, and the number of bits to consider is at most 32.
Steps:
• 0 <= left <= right <= 231 - 1
Assumptions:
• Both left and right are within the given constraints.
Input: left = 10, right = 12
Explanation: In this example, the numbers between 10 and 12 are 10, 11, and 12. The bitwise AND of these numbers is 8, because 10 (1010 in binary), 11 (1011 in binary), and 12 (1100 in binary) all share the prefix 1000.

Input: left = 0, right = 0
Explanation: If left and right are both 0, the bitwise AND of the range [0, 0] is 0.

Input: left = 1, right = 2147483647
Explanation: In this case, the bitwise AND of all numbers from 1 to 2147483647 will result in 0, because at least one bit in every position will be different across such a large range.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus