Problem: Minimum Bit Flips to Convert Number (LeetCode Problem 2220)
In this problem, you are given two integers start
and goal
, and you need to determine the minimum number of bit flips required to convert start
to goal
. A bit flip changes a bit’s value from 0 to 1 or from 1 to 0.
Approach:
- XOR Operation: XOR (
^
) betweenstart
andgoal
will result in a binary number where each1
represents a bit that is different between the two numbers. - Count the Number of
1
s: The number of1
s in the result of the XOR operation gives the number of bit flips required.
Solution in JavaScript:
// Function to calculate minimum bit flips to convert start to goal
function minBitFlips(start, goal) {
// XOR the two numbers to get a result where 1s represent differing bits
let xorResult = start ^ goal;
// Count the number of 1s in the XOR result (which gives the number of bit flips)
let count = 0;
// Loop to count the number of 1s in the XOR result
while (xorResult > 0) {
count += xorResult & 1; // Check if the least significant bit is 1
xorResult >>= 1; // Right shift the result to check the next bit
}
return count; // Return the number of bit flips required
}
// Example usage:
let start = 10; // Binary: 1010
let goal = 7; // Binary: 0111
// Minimum bit flips required to convert 10 to 7
console.log(minBitFlips(start, goal)); // Output: 3
Explanation:
- XOR Operation: XOR between
start
andgoal
highlights all the differing bits. For example:
start = 10 (binary: 1010)
goal = 7 (binary: 0111)
start ^ goal = 1101
(4-bit number where 1s represent different bits).
- Counting 1s: Each
1
in the XOR result corresponds to a bit that needs to be flipped. By counting the number of1
s in the XOR result, we determine the number of bit flips needed to convertstart
togoal
.
Time Complexity:
- O(log N) where
N
is the maximum ofstart
orgoal
. The time complexity is determined by the number of bits in the binary representation of the numbers.