leetcode 1318 Minimum Flips to Make a OR b Equal to c

Posted 琴影

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 1318 Minimum Flips to Make a OR b Equal to c相关的知识,希望对你有一定的参考价值。

Given 3 positives numbers ab 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 OR b == 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 };

以上是关于leetcode 1318 Minimum Flips to Make a OR b Equal to c的主要内容,如果未能解决你的问题,请参考以下文章

leetcode:Minimum Subarray

leetcode@ [310] Minimum Height Trees

LeetCode -- Minimum Path Sum

LeetCode 2187. Minimum Time to Complete Trips

[LeetCode]Minimum Path Sum

leetcode 310. Minimum Height Trees 最小高度树(中等)