Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find bitwise AND of range of numbers in given range in Python
Suppose we have two values start and end, we have to find the bitwise AND of all numbers in the range [start, end] (both inclusive).
So, if the input is like start = 8 end = 12, then the output will be 8. Here's why: 8 is 1000 in binary and 12 is 1100 in binary, so 1000 AND 1001 AND 1010 AND 1011 AND 1100 is 1000 which is 8.
Algorithm
To solve this, we will follow these steps ?
- n := end - start + 1
- x := 0
- for b in range 31 to 0, decrease by 1, do
- if 2^b < n, then
- come out from loop
- if 2^b AND start AND end is non-zero, then
- x := x + (2^b)
- if 2^b < n, then
- return x
Implementation
Let us see the following implementation to get better understanding ?
def solve(start, end):
n = end - start + 1
x = 0
for b in range(31, -1, -1):
if (1 << b) < n:
break
if (1 << b) & start & end:
x += 1 << b
return x
start = 8
end = 12
result = solve(start, end)
print(f"Bitwise AND of range [{start}, {end}]: {result}")
The output of the above code is ?
Bitwise AND of range [8, 12]: 8
How It Works
The algorithm works by checking each bit position from the most significant bit (31st bit) to the least significant bit. For a bit position to be set in the final result, it must be set in both the start and end values, and the range size must be small enough that the bit doesn't get cleared by intermediate values.
Alternative Approach
Here's a simpler approach using bit manipulation ?
def bitwise_and_range(start, end):
shift = 0
# Find the common prefix of start and end
while start != end:
start >>= 1
end >>= 1
shift += 1
return start << shift
# Test with the same example
start = 8
end = 12
result = bitwise_and_range(start, end)
print(f"Bitwise AND of range [{start}, {end}]: {result}")
# Test with another example
start2 = 5
end2 = 7
result2 = bitwise_and_range(start2, end2)
print(f"Bitwise AND of range [{start2}, {end2}]: {result2}")
The output of the above code is ?
Bitwise AND of range [8, 12]: 8 Bitwise AND of range [5, 7]: 4
Conclusion
The bitwise AND of a range can be efficiently computed by finding the common binary prefix of the start and end values. Both approaches work, but the second method is more intuitive and easier to understand.
