Problem Description
You are given three positive integers a, b and c.
Find the minimum number of bit flips in a and b required so that a OR b (bitwise OR) equals c.
A flip operation consists of changing any single bit from 1 to 0 or from 0 to 1 in the binary
representation.
Constraints
- Each argument is in the range from 1 to 109
Examples
Input: a = 2, b = 6, c = 5
Answer: 3
We need to flip the three highlighted bits.
Solution
To solve the problem, we represent a, b and c in binary and compare them bit by bit.
Missing bits are filled with leading zeros.
If a bit of c is 1, at least one of the bits at the same position in a and b must be 1
for a | b == c to hold. If both bits in a and b are 0, we need to flip one of them to one.
It doesn't matter which one, since the result is the same.
If a bit of c is 0, the bits in both a and b must be zero for a | b == c to hold.
In this case we need to flip a bit in a or b only if it is 1.
How do we get the binary representation of a number?
We don't actually need to convert the number to binary. A small math trick is enough.
- To get the lowest bit of a number (the rightmost one), take the remainder of dividing the number by 2.
This works because even numbers always have a lowest bit of
0, and odd numbers always have1. - To drop the lowest bit, integer-divide the number by 2. This gives a new number whose binary representation equals the previous one without its lowest bit.
So we need a loop that checks the lowest bits of all numbers on each iteration, updates the counter,
and then shifts the numbers. The loop runs until all numbers become 0.
export const minFlips = (a: number, b: number, c: number): number => {
let res = 0;
while (a > 0 || b > 0 || c > 0) {
let bitA = a % 2;
let bitB = b % 2;
let bitC = c % 2;
a = Math.floor(a / 2);
b = Math.floor(b / 2);
c = Math.floor(c / 2);
if ((bitA | bitB) == bitC) {
// The condition already holds, so the bits at this position do not need to change
continue;
}
if (bitC == 0) {
res += bitA + bitB;
} else {
res += 1;
}
}
return res;
};Complexity Analysis
Time Complexity
O(log n), where n is the largest of the numbers, since each iteration drops one bit and a number has about log2 n bits.
Given the 109 limit, that's at most about 30 iterations, so effectively constant.
Space Complexity
O(1).