InterviewPrepKit

Home / Coding / Bit Manipulation

Minimum Flips to Make a OR b Equal to c

medium Original β†—
Solving tips
  • OR is evaluated per bit, so decide each position independently and sum the costs.
  • Per-bit rule: if c's bit is 0, both a and b must become 0, cost = ai + bi (this is 2 when both are 1); if c's bit is 1, cost is 1 only when both a and b are 0.
  • Bit-parallel form: turn_on = popcount(c & ~a & ~b), plus popcount(a & ~c) and popcount(b & ~c) added separately (so the double-flip case charges 2).
  • Target O(1) time (32 fixed bits), O(1) space; pitfall: don't undercount the c=0-both-1 case as a single flip, and don't confuse OR with XOR.

Problem

You are given three non-negative integers a, b, and c. In one operation you may flip a single bit of a or of b (change a 0 to 1 or a 1 to 0). Return the minimum number of flips needed so that a OR b == c (bitwise OR).

Examples

  • a = 2, b = 6, c = 5 β†’ 3 β€” a = 010, b = 110, c = 101. Bit 0: c wants 1 but both are 0 β†’ 1 flip. Bit 1: c wants 0 but both are 1 β†’ 2 flips. Bit 2: already fine. Total 3.
  • a = 4, b = 2, c = 7 β†’ 1 β€” a = 100, b = 010, c = 111; only bit 0 (both 0, c wants 1) needs a flip.
  • a = 1, b = 2, c = 3 β†’ 0 β€” 01 OR 10 = 11 = c already.

Constraints

  • 0 <= a, b, c <= 10^9

Think about it first

Hint 1 The OR is computed independently at each bit position, so you can decide each position on its own and add up the costs.
Hint 2 If `c`'s bit is `0`, then `a`'s and `b`'s bits there must *both* be `0` β€” flip each one that's currently `1`. If `c`'s bit is `1`, you only need *one* of them to be `1` β€” so it costs a flip only when both are `0`.
Hint 3 Walk all 32 bit positions and sum those per-bit costs β€” or express the same rules as whole-word masks and count set bits: `c & ~a & ~b` are the bits to turn on, and `a & ~c` plus `b & ~c` are the bits to turn off.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.