forked from SamirPaulb/DSAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 12. Minimum Flips to Make a OR b Equal to c.py
- Loading branch information
1 parent
57747cd
commit ed0dc45
Showing
1 changed file
with
17 additions
and
0 deletions.
There are no files selected for viewing
17 changes: 17 additions & 0 deletions
17
17_Bit-Manipulation/12. Minimum Flips to Make a OR b Equal to c.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
# https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/ | ||
|
||
class Solution: | ||
def minFlips(self, a: int, b: int, c: int) -> int: | ||
res = 0 | ||
for i in range(32): | ||
if (a & 1) | (b & 1) != (c & 1): | ||
if (c & 1) == 1: # (a & 1) | (b & 1) should be == 1 ; so changing any of a, b we can get 1 | ||
res += 1 | ||
else: # (a & 1) | (b & 1) should be == 0 ; is (a & 1) == 1 and (b & 1) == 1 we need to change both to 0 so res += 1; if any of them is 1 then change only 1 i.e. res += 1 | ||
res += (a & 1) + (b & 1) | ||
a, b, c = a>>1, b>>1, c>>1 # left-shift by 1 | ||
|
||
return res | ||
|
||
# Time: O(1) | ||
# Space: O(1) |