// JavaScript program to change least bits to
// get desired OR value
// Returns max of three numbers
function max(a, b, c)
{
return Math.max(a, Math.max(b, c));
}
// Returns count of bits in N
function bitCount(N)
{
let cnt = 0;
while (N > 0)
{
cnt++;
N >>= 1;
}
return cnt;
}
// Returns bit at 'pos' position
function at_position(num, pos)
{
let bit = num & (1<<pos);
return (bit != 0) ? true : false;
}
// Utility method to toggle bit at
// 'pos' position
function toggle(num, pos)
{
num ^= (1 << pos);
return num;
}
// method returns minimum number of bit flip
// to get T as OR value of A and B
function minChangeToReachTaregetOR(A, B, K, T)
{
let maxlen = Math.max(bitCount(A), bitCount(B),
bitCount(T));
// Loop over maximum number of bits among
// A, B and T
for (let i = maxlen - 1; i >= 0; i--)
{
let bitA = at_position(A, i);
let bitB = at_position(B, i);
let bitT = at_position(T, i);
// T's bit is set, try to toggle bit
// of B, if not already
if (bitT )
{
if ((!bitA) && (!bitB))
{
B = toggle(B, i);
K--;
}
}
else
{
// if A's bit is set, flip that
if (bitA)
{
A = toggle(A, i);
K--;
}
// if B's bit is set, flip that
if (bitB)
{
B = toggle(B, i);
K--;
}
}
}
// if K is less than 0 then we can make A|B == T
if (K < 0)
{
console.log("Not possible");
return;
}
// Loop over bits one more time to minimise
// A further
for (let i = maxlen - 1; K > 0 && i >= 0; --i)
{
let bitA = at_position(A, i);
let bitB = at_position(B, i);
let bitT = at_position(T, i);
if (bitT)
{
// If both bit are set, then Unset
// A's bit to minimise it
if (bitA && bitB)
{
A = toggle(A, i);
K--;
}
}
// If A's bit is 1 and B's bit is 0,
// toggle both
if (bitA && !bitB && K >= 2)
{
A = toggle(A, i);
B = toggle(B, i);
K -= 2;
}
}
// Output changed value of A and B
console.log(A, B);
}
// Driver code
let A = 175, B = 66, K = 5, T = 100;
minChangeToReachTaregetOR(A, B, K, T);
//This code is contributed by phasing17