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.
The algorithm efficiently counts the minimum number of bit flips needed by examining each bit position independently. For each bit, it determines if a flip is required in a or b to make (a | b) match c, minimizing unnecessary operations.
classSolution {
publicintminFlips(int a, int b, int c) {
int flips = 0;
for (int i = 0; i < 32; i++) {
int abit = (a >> i) & 1;
int bbit = (b >> i) & 1;
int cbit = (c >> i) & 1;
if (cbit == 1) {
if (abit == 0 && bbit == 0) flips++;
} else {
if (abit == 1) flips++;
if (bbit == 1) flips++;
}
}
return flips;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
public:int minFlips(int a, int b, int c) {
int flips =0;
for (int i =0; i <32; ++i) {
int abit = (a >> i) &1;
int bbit = (b >> i) &1;
int cbit = (c >> i) &1;
if (cbit ==1) {
if (abit ==0&& bbit ==0) flips++;
} else {
if (abit ==1) flips++;
if (bbit ==1) flips++;
}
}
return flips;
}
};