Number Of Flips Required To Make a|b Equal to c
If you understand the OR operations clearly, then this problem will be a good challenge for your skills. Make sure you have a clear understanding of OR before moving on.
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
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
andb = 0110
, soc = 0101
;
After flips, a
will be 0001
, and b
will be 0100
.
Algorithm:
- Initialize
ans
variable to0
. - Loop through, in the range from 0 to 31
- Initialize
bitA
= (
- Initialize