SDE & MLE Prep

1318. Minimum Flips to Make a OR b Equal to c

Problem

Return the minimum number of single-bit flips in a and b that make a OR b == c.

Example: a = 2, b = 6, c = 5 → 3; a = 4, b = 2, c = 7 → 1

Bits are independent. For each position: if c's bit is 1 we need at least one of a, b set (1 flip if both are 0); if it's 0, every set bit among a, b must be flipped. Equivalently popcount((a | b) ^ c) + popcount(a & b & ~c).

Complexity: O(log max(a, b, c)).

class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        flips = 0
        while a or b or c:
            x, y, z = a & 1, b & 1, c & 1
            flips += (x | y) ^ 1 if z else x + y
            a, b, c = a >> 1, b >> 1, c >> 1
        return flips