Minimum Flips to Make a OR b Equal to c Problem
Description
LeetCode Problem 1318.
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).
Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
Example 1:

Input: a = 2, b = 6, c = 5
Output: 3
Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)
Example 2:
Input: a = 4, b = 2, c = 7
Output: 1
Example 3:
Input: a = 1, b = 2, c = 3
Output: 0
Constraints:
1 <= a <= 10^91 <= b <= 10^91 <= c <= 10^9
Solution
Approach: Bit by Bit
A flip changes one bit of a or b, and the OR of two numbers is computed bit by bit, so every bit position can be fixed on its own. For bit i, let x, y and z be that bit of a, b and c:
- If
zis0, bothxandymust be0, so every1among them costs one flip. This is the case that can cost two flips, whenxandyare both1. - If
zis1, at least one ofxandymust be1. If both are0, one flip is enough; otherwise nothing needs to change.
Adding up the cost of every bit gives the answer. All three numbers are at most 10^9 < 2^30, so checking the low 31 bits covers everything.
Complexity: O(log C) time, where C is the largest of the three numbers (31 steps here), and O(1) extra space.
class Solution:
def minFlips(self, a: int, b: int, c: int) -> int:
flips = 0
for i in range(31): # all three numbers are below 2^30
x, y, z = a >> i & 1, b >> i & 1, c >> i & 1
if z == 0:
flips += x + y # every 1 in a or b must become 0
elif x == 0 and y == 0:
flips += 1 # one of the two must become 1
return flips