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

Information

  • Diffculty: Medium

  • Created: 2020-01-12 16:06:46

  • Last Motified: 2020-01-12 16:06:46

  • Tags: Bit Manipulation

Intuition

For each bit a[i], b[i] and c[i], if c[i] == 0, then a[i] and b[i] must be converted to 0. Else if c[i] == 1, then a[i] or b[i] must be 1 or converted to 1.

Solution

class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        flips = 0
        while a or b or c:
            if c % 2 == 1:
                if a % 2 == 1 or b % 2 == 1:
                    pass
                else:
                    flips += 1
            else:
                if a % 2 == 1:
                    flips += 1
                if b % 2 == 1:
                    flips += 1
            a = a >> 1
            b = b >> 1
            c = c >> 1
        return flips