포스트

[leetcode] Minimum Flips to Make a OR b Equal to c 비트연산 &, |, >>

1318. Minimum Flips to Make a OR b Equal to c Solved Medium Topics [

](#) Companies Hint 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:

  • 1
  • 1
  • 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
    def minFlips(self, a: int, b: int, c: int) -> int:
        # a or b 가 c와 같아지도록 뒤집는 횟수
        flips = 0
        while a>0 or b>0 or c>0:
            # 각 맨 오른쪽 비트 추출
            bit_a = a & 1
            bit_b = b & 1
            bit_c = c & 1

            # 현재 OR 결과가 목표와 다르면 flip 필요
            if (bit_a | bit_b) != bit_c:
                if bit_c == 1:
                    # c가 1이어야 하는데 현재 OR 결과가 0이므로 한번 flip
                    flips += 1 # a나 b 중 하나만 flip
                else:
                    # c가 0이어야 하는데 현재 OR 결과가 1이므로 모두 0으로 flip
                    flips += bit_a + bit_b # 1인 것들 모두 flip
            
            # 다음 비트로 이동
            a >>= 1
            b >>= 1
            c >>= 1
        
        return flips

#leetcode #비트연산 #and #or #shift #bitmanipulation

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.