Minimum Flips to Make a OR b Equal to c LeetCode solution in Python

1
# Runtime: 37 ms (Top 81.40%) | Memory: 13.8 MB (Top 80.93%)
2
class Solution:
3
def minFlips(self, a: int, b: int, c: int) -> int:
4
res = 0
5
for i in range(32):
6
if (a & 1) | (b & 1) != (c & 1):
7
if (
8
c & 1
9
) == 1: # (a & 1) | (b & 1) should be == 1 ; so changing any of a, b we can get 1
10
res += 1
11
else: # (a & 1) | (b & 1) should be == 0 ; is (a & 1) == 1 and (b & 1) == 1 we need to change both to 0 so res += 1; if any of them is 1 then change only 1 i.e. res += 1
12
res += (a & 1) + (b & 1)
13
a, b, c = a >> 1, b >> 1, c >> 1 # right-shift by 1
14

15
return res
16

17

18
# Time: O(1)
19
# Space: O(1)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0