Minimum Flips to Make a OR b Equal to c

Given three positive integers a, b and c, return the minimum number of single-bit flips on a and b needed so that (a OR b) == c. A flip changes one bit of a or b from 0 to 1 or from 1 to 0.

30:00

Minimum Flips to Make a OR b Equal to c
medium
Free written solution
Topics
Companies

Given three positive integers a, b and c, return the minimum number of single-bit flips on a and b needed so that (a OR b) == c. A 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
Constraints:
  • 1≤a,b,c≤1091 \leq a, b, c \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"a":2,"b":6,"c":5}

a = 10, b = 110, c = 101. OR works on each bit column separately, so each column can be fixed on its own.

Fix a | b one column at a time

flips = 0

a
0
0
1
0
b
0
1
1
0
a|b
0
1
1
0
c
0
1
0
1
cost
.
.
.
.
3
2
1
0

c bit = 1

need at least one 1: cost 1 only if a and b are both 0

c bit = 0

both must be 0: cost = a bit + b bit

Variables
VariableValue
a2
b6
c5
DepthFunction Call
Stack empty
0/12