MediumNo. 1318
Minimum Flips to Make a OR b Equal to c — LeetCode 1318 Python Solution
- Pattern
- Bit Manipulation
- Topics
- Bit Manipulation
- On a study list
- LeetCode 75
- 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
- Time
- O(log M)where M is the maximum value of the numbers in the problem
- Space · auxiliary
- O(1)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0029 | Divide Two Integers | Medium |
| 0067 | Add Binary | Easy |
| 0136 | Single Number | Easy |
| 0137 | Single Number II | Medium |
| 0190 | Reverse Bits | Easy |
| 0191 | Number of 1 Bits | Easy |
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.