1 minute read

Problem Statement

leetcode problem link

My Solution [Accepted]

class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        res = 0

        while (a | b) != c:
            a_or_b_right_most_bit = (a | b) & 1
            c_right_most_bit = c & 1
            if a_or_b_right_most_bit != c_right_most_bit:
                a_right_most_bit = a & 1
                b_right_most_bit = b & 1
                c_right_most_bit = c & 1
                if c_right_most_bit == 0:
                    if a_right_most_bit != 0:
                        res += 1
                    if b_right_most_bit != 0:
                        res += 1
                else:
                    res += 1

            a >>= 1
            b >>= 1
            c >>= 1

        return res

Editorial

Approach 1: Bit Manipulation

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

Approach 2: Count the Number of Set Bits Using Built-in Function

# In 3.9 or earlier
class Solution:
    # In 3.9 or earlier
    def minFlips(self, a: int, b: int, c: int) -> int:
        return bin((a | b) ^ c).count("1") + bin(a & b & ((a | b) ^ c)).count("1")

    # In 3.10 or later
    def minFlips(self, a: int, b: int, c: int) -> int:
        return ((a | b) ^ c).bit_count() + (a & b & ((a | b) ^ c)).bit_count()