2220. Minimum Bit Flips to Convert Number #521
-
Topics: A bit flip of a number
Given two integers Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine how many bit positions differ between Steps:
Let's implement this solution in PHP: 2220. Minimum Bit Flips to Convert Number <?php
/**
* @param Integer $start
* @param Integer $goal
* @return Integer
*/
function minBitFlips($start, $goal) {
// Step 1: XOR start and goal to find the differing bits
$xor = $start ^ $goal;
// Step 2: Count the number of 1's in the binary representation of xor
$bitFlips = 0;
while ($xor > 0) {
// Increment count if the last bit is 1
$bitFlips += $xor & 1;
// Shift xor to the right by 1 bit
$xor >>= 1;
}
return $bitFlips;
}
// Test cases
echo minBitFlips(10, 7); // Output: 3
echo "\n";
echo minBitFlips(3, 4); // Output: 3
?> Explanation:
Time Complexity:
Output:
|
Beta Was this translation helpful? Give feedback.
We need to determine how many bit positions differ between
start
andgoal
. This can be easily achieved using the XOR operation (^
), which returns a 1 for each bit position where the two numbers differ.Steps:
start
andgoal
. The result will be a number that has1
s in all the positions wherestart
andgoal
differ.1
s are present in the binary representation of the result (i.e., the Hamming distance).1
s will give us the minimum number of bit flips needed.Let's implement this solution in PHP: 2220. Minimum Bit Flips to Convert Number