[leetcode] 1318. Minimum Flips to Make a OR b Equal to c _ Algorithm Problem Solve for python



1. Problem

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

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^9
  • 1 <= b <= 10^9
  • 1 <= c <= 10^9

2. Solution

I solved this problem like this.

  • Step
    • Get (a b) and XOR C. If (a b) ^ c bit 1, we have to change a or b.
    • If bit is 0, we don’t need to check that index.
    • If bit is 1,
      • If c is 1, a & b are both 0. We just change 1 bit.
      • If c is 0, a & b are either [(0, 1), (1, 0), (1, 1)]. We change bit and if bit is 1, we change to 0.
class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        answer = 0
        sub = (a | b) ^ c
        size = len(bin(a | b | c)) - 2 
        for i in range(size):
            x = bin(sub)[2:].zfill(size)[i]
            if x != '1':
                continue
            if bin(c)[2:].zfill(size)[i] == '1':
                answer += 1
            else:
                answer += int(bin(a)[2:].zfill(size)[i]) + int(bin(b)[2:].zfill(size)[i])

        return answer

Other solution is more better.

class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        return ((a | b) ^ c).bit_count() + (a & b & ((a | b) ^ c)).bit_count()