#1318
Minimum Flips to Make a OR b Equal to c
MediumBit ManipulationBit ManipulationGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(1) | O(1) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(1)Space O(1)
The optimal solution uses bit manipulation to directly assess the bits of a, b, and c without unnecessary iterations. It focuses on the conditions that dictate whether a flip is needed.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a flips counter to 0.
- 2Step 2: For each bit position from 0 to 31, extract the bits of a, b, and c.
- 3Step 3: If the c bit is 0, count the number of 1s in a and b at that position (both need to be flipped).
- 4Step 4: If the c bit is 1, check if both a and b are 0 (both need to be flipped to 1).
solution.py13 lines
1# Full working Python code
2
3def minFlips(a, b, c):
4 flips = 0
5 for i in range(32):
6 a_bit = (a >> i) & 1
7 b_bit = (b >> i) & 1
8 c_bit = (c >> i) & 1
9 if c_bit == 0:
10 flips += a_bit + b_bit
11 else:
12 flips += (1 - (a_bit | b_bit))
13 return flipsℹ
Complexity note: The optimal solution also runs in O(1) time as we are still iterating through a fixed number of bits (32).
- 1Understanding bit manipulation is crucial for solving problems involving binary representations.
- 2Flipping bits can be visualized as toggling switches, where each switch represents a binary digit.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.