Minimum Flips to Make a OR b Equal to c

Count the fewest bit flips in a and b that make a OR b equal c, one bit position at a time.

Given three positive integers a, b and c, return the smallest number of bit flips in a and b that makes the bitwise OR of a and b, written a | b in Java, equal to c. One flip changes one bit of a or b from 0 to 1 or from 1 to 0.

Example 1
Input: a = 2, b = 6, c = 5
Output: 3
Explanation: after the flips a = 1 and b = 4, and 1 | 4 = 5.
Example 2
Input: a = 4, b = 2, c = 7
Output: 1
Explanation: flipping the lowest bit of a gives a = 5, and 5 | 2 = 7.
Example 3
Input: a = 1, b = 2, c = 3
Output: 0
Explanation: 1 | 2 is already 3.
Solution

The Idea

Picture a row of lamps, each wired to two switches, one in a top row and one in a bottom row. A lamp is lit when at least one of its two switches is on. You are told which lamps should be lit, and you want to get there by flipping as few switches as possible. That is this problem: the switches are the bits of a and b, the lamps are the bits of a | b, and c is the pattern of lamps you want.

To see the switches, write the numbers in binary. In Example 1, 2 is 010, 6 is 110 and 5 is 101. Each digit is one bit, and the bit positions are counted from the right, starting at 0. Position 0 is worth 1, position 1 is worth 2 and position 2 is worth 4, so 5 = 4 + 1 has its 1 bits at positions 2 and 0.

The bitwise OR compares two numbers position by position, and its bit is 1 when at least one of the two bits is 1. So 2 | 6 is 110, which is 6, while c wants 101. Look at the picture below.

Example 1 in binary, with bit position 0 on the right: a = 010, b = 110, a OR b = 110, c = 101. Position 2 needs 0 flips, position 1 needs 2 flips, position 0 needs 1 flip, 3 in total.

Each column is one bit position. In the teal column, position 2, a has 0 and b has 1, so the row labelled a OR b = 6 already shows the 1 that the row labelled c = 5 (wanted) asks for. Nothing needs to change there.

At position 1, both a and b have a 1, but c wants 0. Turning off one of them is not enough, because the other still lights the lamp, so both must be flipped: 2 flips. At position 0 both bits are 0 and c wants 1, so flipping either one will do: 1 flip. That makes 0 + 2 + 1 = 3, the answer of Example 1. If the flip at position 0 goes to a, the three flips end with a = 001 and b = 100, the 1 and 4 of the explanation.

Did the flips at one position change what another position needed? No. The OR at position 1 only looks at the two bits at position 1. So each position is a small problem of its own, and the answer is the sum of the flips each position needs. Those flips depend on just three bits: the one in c and the two in a and b.

Solution Approach

Turning that into code means settling three things: why the positions can be handled one by one instead of trying sets of flips, how many flips one position needs, and how to read the bits one position at a time. There is also an optional shorter version that works on whole numbers at once.

Positions instead of sets of flips

Why not try different sets of flips until a | b equals c? Each bit of a and b can be flipped or left alone. With three bits each, as in Example 1, that is already 26 = 64 sets to try.

How many bits can a and b have in real inputs? Each is a Java int of 32 bits, kept in two's complement form, which sets position 31 only for a negative value. Because the three inputs here are positive, their 1 bits sit at positions 0 to 30. Together, a and b can have 62 bits that matter, so 262 sets of flips. Settling each of the 31 positions on its own avoids all of that.

Flips needed at one position

How many flips does one position need? It depends on the bit of c. When that bit is 1, at least one of the bits of a and b must be 1. If both are 0, one flip turns either of them on; otherwise no flip is needed.

When the bit of c is 0, both bits must be 0, so every 1 among them costs one flip. That is 0, 1 or 2 flips, which is just the bit of a plus the bit of b. Position 1 in the picture is the case with 2. Counting one flip at each position where a | b is wrong misses that second flip, and gives 2 instead of 3 for Example 1.

Reading one bit at a time

How do we get at a single bit? The bitwise AND, &, gives a 1 at a position only when the two numbers both have a 1 there. The number 1 has its only 1 bit at position 0, so a & 1 keeps the bit at position 0 and clears the rest. For b = 6, which is 110, the result is 0.

To reach the next position, shift the number right by one with b >>= 1. Every bit moves one position to the right, and the bit at position 0 drops off. The 6 (110) becomes 3 (011), so the bit that was at position 1 is now at position 0. Shifting a, b and c together keeps all three on the same position.

When can the reading stop? Once a, b and c are all 0, every position still to come has three 0 bits. The bit of c is 0 there, and neither a nor b has a 1 to turn off, so those positions cost nothing.

Optional: counting with whole numbers

Can the bit-by-bit reading be skipped? Java's Integer.bitCount(x) returns how many 1 bits x has. The bitwise XOR, ^, gives a 1 where two bits differ, so (a | b) ^ c has a 1 at each position where a | b is wrong, one flip each. The bitwise NOT, ~c, turns every bit of c around. So a & b & ~c has a 1 where a and b are both 1 and c is 0, the positions that need the second flip:

Java
int flips = Integer.bitCount((a | b) ^ c) + Integer.bitCount(a & b & ~c);

For Example 1, (a | b) ^ c is 110 ^ 101 = 011, two 1 bits, and a & b & ~c is 010, one more, so 3 again. This line and a bit-by-bit loop gave the same count for a million random positive inputs, and for every choice of a, b and c from 1 to 63.

Java Solution

The method minFlips works in these steps:

  1. First, set flips, the running total, to 0.
  2. Start a loop that runs while a, b or c is not 0. Inside, read the bit at position 0 of each number with & 1, into bitA, bitB and bitC.
  3. If bitC is 1, add 1 to flips only when bitA | bitB is 0, that is, when both bits are 0.
  4. If bitC is 0, add bitA + bitB, one flip for each 1 that must be turned off.
  5. Shift a, b and c right by one with >>= 1, so the next position moves to position 0.
  6. When the loop ends, return flips.

The main method runs the three examples, then a = b = 7 with c = 1, where two positions need 2 flips each, then numbers of different lengths, and finally a = Integer.MAX_VALUE, which has a 1 at every position from 0 to 30.

Java
public class MinimumFlips {

    public static int minFlips(int a, int b, int c) {
        int flips = 0;
        while (a != 0 || b != 0 || c != 0) {
            int bitA = a & 1;
            int bitB = b & 1;
            int bitC = c & 1;
            if (bitC == 1) {
                if ((bitA | bitB) == 0) {
                    flips += 1;          // turn on either bit
                }
            } else {
                flips += bitA + bitB;    // every 1 must become 0
            }
            a >>= 1;
            b >>= 1;
            c >>= 1;
        }
        return flips;
    }

    public static void main(String[] args) {
        System.out.println(minFlips(2, 6, 5));
        System.out.println(minFlips(4, 2, 7));
        System.out.println(minFlips(1, 2, 3));
        System.out.println(minFlips(7, 7, 1));
        System.out.println(minFlips(8, 3, 5));
        System.out.println(minFlips(Integer.MAX_VALUE, 1, 1));
    }
}

Running it prints:

Output
3
1
0
4
3
30

The 3, 1 and 0 at the top match Examples 1, 2 and 3. The 4 on the fourth line comes from a = b = 111 and c = 001. At positions 1 and 2 both a and b have a 1 where c wants 0, and each of those positions costs 2 flips.

The fifth line, 3, compares numbers of different lengths: a = 8 is 1000, b = 3 is 0011 and c = 5 is 0101. Position 0 is already right, the 1 of b at position 1 must go, position 2 needs a 1, and the 1 of a at position 3 must go.

Look at the last line, 30. Integer.MAX_VALUE is 2,147,483,647, a 1 at each of the 31 positions 0 to 30. With c = 1, position 0 is fine, and the 1 at each of positions 1 to 30 costs one flip. The loop kept going until all 31 positions of a were read.

Complexity

The loop does a fixed amount of work per bit position, and the largest of the three numbers decides how many positions there are.

  • Time: O(log max(a, b, c)), because each pass shifts all three numbers right by one position, and the loop ends once the largest of them has no 1 bits left, after at most 31 passes for a positive int.
  • Space: O(1), because the method keeps only flips and the three bits of the current position, and shifts its own copies of a, b and c.