Problem 1318 · LeetCode 1318(opens in a new tab)
Minimum Flips to Make a OR b Equal to c
MediumBit manipulation
You are given three positive integers a, b and c. One flip changes a single bit of a or of b, from 0 to 1 or from 1 to 0.
Return the smallest number of flips that makes a | b (bitwise OR) equal to c.
Example 1
Input: a = 10, b = 7, c = 9 Output: 3 Why: bit 1 needs both 1s cleared, bit 2 needs b's 1 cleared
2 more examples and the constraints
Example 2
Input: a = 8, b = 1, c = 12 Output: 2 Why: clear bit 0 of b and set bit 2 of either number
Example 3
Input: a = 4, b = 3, c = 7 Output: 0 Why: 4 | 3 is already 7
Constraints
- 1 ≤ a ≤ 1,000,000,000
- 1 ≤ b ≤ 1,000,000,000
- 1 ≤ c ≤ 1,000,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check bit by bitO(log c)
- Count with masksO(1)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for one input | Verdict |
|---|---|---|---|
| Check bit by bit | O(log c) | Clear; 31 small checks | |
| Count with masks | O(1) | Best; a few word-wide operations |
Both are tiny: the inputs fit in 31 bits.
Edge cases to test
- Already equal. a = 4, b = 3, c = 7 gives 0.
- Both numbers hold a bit c lacks. a = 6, b = 6, c = 1 costs 2 per such bit, plus 1 for c's missing bit: 5.
- c has a bit neither has. a = 1, b = 1, c = 6: set bits 1 and 2 (one flip each) and clear bit 0 in both (two flips): 4.
- Large values. Up to 1,000,000,000 fits in 30 bits, so 31 positions cover everything.
Common mistakes
- Counting one flip where c has 0 and both a and b have 1; both must be cleared.
- Counting two flips where c has 1 and both a and b have 0; one is enough.
- Returning only the bit count of
(a | b) ^ c, which misses the double-cost positions.
How to talk through it
- 1Clarify. Can I flip bits in a and b only, not c? Is every flip worth 1?
- 2Notice independence. OR is computed per bit, so each position can be fixed on its own.
- 3List the cases. c bit 1 with both 0: one flip. c bit 0: one flip per 1 in a and b.
- 4Vectorise. Count
(a | b) ^ cfor the wrong bits and adda & b & ~cfor the double ones. - 5Test out loud. Run an already-equal triple, a bit both numbers share that c lacks, and a missing bit.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?