Search⌘ K

Number Of Flips Required To Make a|b Equal to c

Understand how to calculate the minimum flips needed to make the bitwise OR of two numbers equal to a third number. Learn the algorithm to compare bits, flip bits efficiently, and implement a solution with O(log n) time and O(1) space complexity.

Introduction

In this question, we will flip the bits to make two numbers equal to the third number.

Let’s see how to achieve this using the OR operator.

Problem statement

We need to write a program with minimum flips to make the two bits’ OR operation equal a number.

Input: a = 2, b = 6, c = 5
 
Output: 3

Explanation: After flips, a = 1 , b = 4 , c = 5 such that (a OR b == c).

Assume n is non-negative. Use the | operator to achieve this.

Solution

We have three positives numbers, a, b, and c. We have to find the minimum flips required in some bits of a, b to make (a OR (b == c)). Here we are considering Bitwise OR operation. The flip operation consists of changing any single bit 1 to 0 or changing the bit 0 to 1 in their binary representation.

If, a = 0010 and b = 0110, so c = 0101;

After flips, a will be 0001, and b will be 0100.

Algorithm:

  • Initialize ans variable to 0.
  • Loop through, in the range from 0 to 31
    • Initialize
      • bitA = (a2i\frac{a}{2^{i}}
...