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
). (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: 1
Example 3:
Input: a = 1, b = 2, c = 3 Output: 0
class Solution { public int minFlips(int a, int b, int c) { int res = 0; for(int i = 0; i < 31; i++, a = a >> 1, b = b >> 1, c = c >> 1 ){ int t = a & 1; int m = b & 1; int n = c & 1; if ((t | m) != n) { if (n == 0) { if (t == 1) { res++; } if (m == 1) { res++; } } else { res++; } } } return res; } }
来自https://leetcode.com/problems/minimum-flips-to-make-a-or-b-equal-to-c/discuss/477683/Java-Bit
a|b反转多少位等于c,每个数是32位,总共可以翻31次。在每一位上判断和c的关系,如果不相等就继续判断,
1.c是0,a|b不是接着往下判断,可能翻转1位或2位
2. c是1,a|b不是,此时翻转一位即可