Minimum Flips to Make a OR b Equal to c
Master this topic with zero to advance depth.
Minimum Flips to Make a OR b Equal to c
Given 3 positives a, b and c. Return the minimum flips required in some bits of a and b to make (a OR b == c).
Examples
Level I: Brute Force (Bit-by-Bit Check)
Intuition
Iterate through each bit of the three numbers and compare the required state c with the current state a | b. Count the flips needed for each bit position.
Thought Process
- For each bit position (0 to 31):
- If -th bit of
cis 0:- Both -th bits of
aandbmust be 0. Add their sum toflips.
- Both -th bits of
- If -th bit of
cis 1:- At least one of -th bits of
aorbmust be 1. If both are 0, add 1 toflips.
- At least one of -th bits of
- If -th bit of
- Return
flips.
Pattern: Positional Verification
Level II: Iterative with Built-in Counting
Intuition
Instead of checking every bit manually, we can use built-in bit counting functions to calculate the flips needed for the entire numbers after identifying which bits are incorrect via XOR and AND.
Level III: Optimal (Bitwise Magic)
Intuition
We can use bitwise operators to find all differing bits at once. (a | b) ^ c gives bits that are incorrect. We then handle the cases where c bit is 0 separately as they might require 2 flips per bit.
Thought Process
incorrect = (a | b) ^ c.must_flip_two = a & b & incorrect.- Flips = Count of set bits in
incorrect+ Count of set bits inmust_flip_two.
Pattern: Composite Bitmasking
Detailed Dry Run
a=2(0010), b=6(0110), c=5(0101) a|b = 6 (0110) incorrect = 0110 ^ 0101 = 0011 (bits 0 and 1 are wrong) must_flip_two = 0010 & 0110 & 0011 = 0010 (bit 1 is wrong and both a,b are 1) Total = popcount(0011) + popcount(0010) = 2 + 1 = 3.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.