【leetcode】1318. Minimum Flips to Make a OR b Equal to c
题目如下:
Given 3 positives numbers
a
,b
andc
. Return the minimum flips required in some bits ofa
andb
to make (a
ORb
==c
). (bitwise OR operation).
Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.Example 1:
Input: a = 2, b = 6, c = 5 Output: 3 Explanation: After flips a = 1 , b = 4 , c = 5 such that (a
ORb
==c
)Example 2:
Input: a = 4, b = 2, c = 7 Output: 1Example 3:
Input: a = 1, b = 2, c = 3 Output: 0Constraints:
1 <= a <= 10^9
1 <= b <= 10^9
1 <= c <= 10^9
解题思路:本题很简单。如果c某一位是0,那么需要a和b相应的那一位都是0,翻转次数为a和b相应位1的个数;如果c的某位是1,那么只有a和b对应位都是0的情况下做两次翻转。
代码如下:
class Solution(object): def minFlips(self, a, b, c): """ :type a: int :type b: int :type c: int :rtype: int """ res = 0 na = bin(a)[2:].rjust(32, '0'); nb = bin(b)[2:].rjust(32, '0'); nc = bin(c)[2:].rjust(32, '0'); for i in range(32): ia,ib,ic = int(na[i]),int(nb[i]),int(nc[i]) if ia | ib == ic:continue elif ic == 0: res += 1 if ia * ib == 0 else 2 else: res += 1 return res