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.
Input: a = 2, b = 6, c = 5
Output: 3
Explanation: After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)
Input: a = 4, b = 2, c = 7
Output: 1
Input: a = 1, b = 2, c = 3
Output: 0
From: LeetCode
Link: 1318. Minimum Flips to Make a OR b Equal to c
This function works by checking each bit position from the least significant bit to the most significant bit, calculating whether a flip is needed at each position, and then shifting the numbers to the right to check the next position. The count of flips is increased based on the bits of a, b, and c.
int minFlips(int a, int b, int c) {
int flips = 0;
// Loop through each bit position until a, b, and c are all zero.
while (a > 0 || b > 0 || c > 0) {
// Check the rightmost bits of a, b, and c.
int bit_a = a & 1;
int bit_b = b & 1;
int bit_c = c & 1;
if ((bit_a | bit_b) != bit_c) {
// If a OR b is not equal to c at this bit, we need to flip.
if (bit_c == 0) {
// If c is 0, both a and b must be 0, so flip both if they are not.
flips += bit_a + bit_b;
} else {
// If c is 1, at least one of a or b must be flipped to 1.
flips += 1;
}
}
// Shift a, b, and c to the right by one to check the next bit.
a >>= 1;
b >>= 1;
c >>= 1;
}
return flips;
}