leetcode 1318 Minimum Flips to Make a OR b Equal to c
作者:互联网
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
Constraints:
1 <= a <= 10^9
1 <= b <= 10^9
1 <= c <= 10^9
题目大意:给定三个数a, b, c,对a,b,c的二进制表示,每修改二进制比特中的一位为1次,返回修改a和b的最少次数,使得a or b = c.
思路:我们先计算a or b, 然后让其结果的二进制和c的二进制一位一位的进行比较,如果某一位不同,则需要修改a或者b,假如某一位c为0, 而a or b对应的为1,则要考虑a和b对应的是不是都为1,如果都为1,则都要改,修改次数加2,否则只要修改一个,如果某一位c为1,则只要修改a或者b中那一位为1,修改次数加1.
1 class Solution { 2 public: 3 int minFlips(int a, int b, int c) { 4 int cnt = 0; 5 int A = a | b; 6 while (A || c) { 7 int d1 = c & 1, d2 = A & 1; 8 if (d1 != d2) { 9 if ((d1 == 0) && ((a & 1) == 1 && (b & 1) == 1)) 10 cnt += 2; 11 else 12 cnt++; 13 } 14 c >>= 1; 15 A >>= 1; 16 a >>= 1; 17 b >>= 1; 18 } 19 return cnt; 20 } 21 };
标签:cnt,二进制,int,Make,Flips,Equal,修改,一位,d1 来源: https://www.cnblogs.com/qinduanyinghua/p/12187628.html