InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Minimum Flips to Make a OR b Equal to c

medium Original ↗ 00:00

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 = 53a = 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 = 71a = 100, b = 010, c = 111; only bit 0 (both 0, c wants 1) needs a flip.
  • a = 1, b = 2, c = 3001 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug