![]() |
VOOZH | about |
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
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
Using XOR Operator: 4
Time Complexity: O(log(max(A, B)))
Auxiliary Space: O(1)
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
Using AND Operator: 4
Time Complexity: O(log(max(A, B)))
Auxiliary Space: O(1)