Given two numbers, A and B. Write a program to count the number of bits needed to be flipped to obtain B from A.
Examples:
Input: A = 10, B = 20
Output: 4
Explanation: Binary representation of A is 00001010
Binary representation of B is 00010100
We need to flip highlighted four bits in A to obtain B from it.Input: A = 7, B = 10
Output: 3
Explanation: Binary representation of A is 00000111
Binary representation of B is 00001010
We need to flip highlighted three bits in A to obtain B from it.
Below are the approaches to Count Number of Bits to be Flipped to Convert A to B using JavaScript:
Table of Content
Using the XOR operator
We can use the XOR operator (^) to find the bits that are different between A and B. Then, we count the number of set bits (bits with value 1) in the result.
Example: Implementation of a program to find the Number of bits to be flipped to obtain B from A using the XOR operator
function countBitsToFlipXOR(A, B) {
// Find the bits that are different between A and B
let xorResult = A ^ B;
let count = 0;
// Count the number of set bits in the XOR result
while (xorResult > 0) {
// Check if the least significant bit is 1
count += xorResult & 1;
xorResult >>= 1; // Right shift to check the next bit
}
return count;
}
const A1 = 10, B1 = 20;
console.log("Using XOR Operator:", countBitsToFlipXOR(A1, B1));
Output
Using XOR Operator: 4
Time Complexity: O(log(max(A, B)))
Auxiliary Space: O(1)
Using the AND operator
We first Iterate through each bit of numbers A and B and than use AND operator to extract the least significant bit of A and B.If the bits are different, increment the flips count, and then right shift A and B to check the next bit.
Example: Implementation of program to find Number of bits to flipped to obtain B from A using the AND operator
function countBitsToFlipAND(a, b) {
let flips = 0; // initially flips is equal to 0
let t1, t2;
// Loop through each bit of A and B
while (a > 0 || b > 0) {
t1 = a & 1; // Extract the least significant bit of A
t2 = b & 1; // Extract the least significant bit of B
// If the bits are different, increment the flips count
if (t1 !== t2) {
flips++;
}
// Right shift A and B to check the next bit
a >>= 1;
b >>= 1;
}
// Return the total flips count
return flips;
}
const A1 = 10, B1 = 20;
console.log("Using AND Operator:", countBitsToFlipAND(A1, B1));
Output
Using AND Operator: 4
Time Complexity: O(log(max(A, B)))
Auxiliary Space: O(1)