Closed mah-shamim closed 1 month ago
We need to determine how many bit positions differ between start
and goal
. This can be easily achieved using the XOR operation (^
), which returns a 1 for each bit position where the two numbers differ.
start
and goal
. The result will be a number that has 1
s in all the positions where start
and goal
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
<?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
?>
^
(XOR) operation compares each bit of start
and goal
. If the bits are different, the corresponding bit in the result will be 1
.1
s in the result, which gives the number of differing bits, i.e., the number of bit flips required.& 1
operation checks if the last bit is 1
, and >>= 1
shifts the number right to process the next bit.start
or goal
, because we're checking each bit of the number. In the worst case, we will loop through all bits of a 32-bit integer (since PHP 5.6 works with 32-bit or 64-bit integers depending on the system).start = 10
and goal = 7
, the output is 3
.start = 3
and goal = 4
, the output is 3
.
Discussed in https://github.com/mah-shamim/leet-code-in-php/discussions/521
0 <= start, goal <= 109
**Hint:** 1. If the value of a bit in start and goal differ, then we need to flip that bit. 2. Consider using the XOR operation to determine which bits need a bit flip.