Skip to content

Commit aa2a87c

Browse files
authored
Create 0201-bitwise-and-of-numbers-range.py
1 parent 5171098 commit aa2a87c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# check difference at each bit (cannot be more than left - right)
2+
class Solution:
3+
def rangeBitwiseAnd(self, left: int, right: int) -> int:
4+
res = 0
5+
6+
for i in range(32):
7+
bit = (left >> i) & 1
8+
if not bit:
9+
continue
10+
11+
remain = left % (1 << (i + 1))
12+
diff = (1 << (i + 1)) - remain
13+
if right - left < diff:
14+
res = res | (1 << i)
15+
return res
16+
17+
# find the longest matching prefix of set bits between left and right
18+
class Solution:
19+
def rangeBitwiseAnd(self, left: int, right: int) -> int:
20+
i = 0
21+
while left != right:
22+
left = left >> 1
23+
right = right >> 1
24+
i += 1
25+
return left << i

0 commit comments

Comments
 (0)