[LeetCode] Minimum Flips to Make a OR b Equal to c

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int minFlips(int a, int b, int c) {
int bit = a | b;
int res = 0;
for(int i = 0; i < 32; i++) {
int ibit = bit & (1<<i), ic = c & (1<<i);
if(ibit == ic) continue;
if(ibit) {
if(a & (1<<i)) res += 1;
if(b & (1<<i)) res += 1;
}
if(ic) res += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/07/PS/LeetCode/minimum-flips-to-make-a-or-b-equal-to-c/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.