Minimum Flips to Make a OR b Equal to c — LeetCode 1318 Python Solution
- Problem
- #1318
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ).
Example
- Input
- a = 2, b = 6, c = 5
- Output
- 3
- Explanation
- After flips a = 1 , b = 4 , c = 5 such that (a OR b == c)
Python solution
class Solution:
def minFlips(self, a: int, b: int, c: int) -> int:
ans = 0
for i in range(32):
x, y, z = a >> i & 1, b >> i & 1, c >> i & 1
ans += x + y if z == 0 else int(x == 0 and y == 0)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log M), where M is the maximum value of the numbers in the problem |
| Space | O(1) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 1318. Minimum Flips to Make a OR b Equal to c is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Bit Manipulation.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 1318. Minimum Flips to Make a OR b Equal to c?
- LeetCode 1318. Minimum Flips to Make a OR b Equal to c is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1318. Minimum Flips to Make a OR b Equal to c?
- The Python solution on this page runs in O(\log M), where M is the maximum value of the numbers in the problem.
- What is the space complexity of LeetCode 1318. Minimum Flips to Make a OR b Equal to c?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1318. Minimum Flips to Make a OR b Equal to c cover?
- LeetCode 1318. Minimum Flips to Make a OR b Equal to c is tagged Bit Manipulation on LeetCode.