Method 1:
class Solution:
def minFlips(self, a: int, b: int, c: int) -> int:
'''
We need to change a and b
Result : a | b = c
| is a bitwise or
'''
binA, binB, binC = bin(a)[2:], bin(b)[2:], bin(c)[2:]
l1 = len(binA)
l2 = len(binB)
l3 = len(binC)
maxLen = max(l1, l2, l3)
binA = binA.zfill(maxLen)
binB = binB.zfill(maxLen)
binC = binC.zfill(maxLen)
ans = 0
for i in range(maxLen):
req = binC[i]
if req == '1':
if binA[i] == '0' and binB[i] == '0':
ans += 1
else:
if binA[i] == '1' and binB[i] == '1':
ans += 2
elif binA[i] == '1' or binB[i] == '1':
ans += 1
return ans
Method 2 (Short):
class Solution:
def minFlips(self, a: int, b: int, c: int) -> int:
'''
We need to find the LSB : Least significant bit i.e. Last binary value
eg. for 100 : 0 is LSB
for 101 : 1 is LSB
We can use '& 1' to get the LSB
For each Iteration we need to shift towards the right
We can use right shift operator >>
eg. 100 >> 1 would become 10
'''
ans = 0
while a or b or c:
bitA = a & 1
bitB = b & 1
bitC = c & 1
if bitC:
ans += not (bitA + bitB)
else:
ans += (bitA + bitB)
a >>= 1
b >>= 1
c >>= 1
return ans