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.
We'll cover the following...
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
nis 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 = 0010andb = 0110, soc = 0101;
After flips, a will be 0001, and b will be 0100.
Algorithm:
- Initialize
ansvariable to0. - Loop through, in the range from 0 to 31
- Initialize
bitA= (
- Initialize