-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_BitwiseAndOfANumber.py
More file actions
38 lines (31 loc) · 1.1 KB
/
06_BitwiseAndOfANumber.py
File metadata and controls
38 lines (31 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Question link - https://leetcode.com/problems/bitwise-and-of-numbers-range/?envType=study-plan-v2&envId=top-interview-150
class Solution:
def rangeBitwiseAnd(self, left: int, right: int) -> int:
# Sol3: Optimal Solution O(logn) with simple left and right
# compartion
i = 0
while left != right:
left = left >> 1
right = right >> 1
i += 1
return left << i
# Sol2: Better Approch - O(logn) , complex solution
# res = 0
# for i in range(32):
# bit = (left >> i) & 1
# # If not 1 , skip
# if not bit:
# continue
# # Diff calculation
# remain = left % (1 << (i + 1))
# diff = (1 << (i + 1)) - remain
# # Right - left < diff
# if right - left < diff:
# # Putting the 1 in output
# res = res | (1 << i)
# return res
# Sol1: Brute Solution with O(n)
# res = 0
# for i in range (left , right):
# res = res & i
# return res