ZhongKuo0228 / study

0 stars 0 forks source link

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

Open fockspaces opened 6 months ago

fockspaces commented 6 months ago

image

From Oberservation, we see: 00 -> 1 : 1 01 -> 1 : 0 11 -> 1 : 0

00 -> 0 : 0 01 -> 0 : 1 11 -> 0 : 2

so we can split into two case

  1. a or b = 1 in single bit
  2. a or b = 0 in single bit

then we just use basic operation to deliver the results

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