2429. Minimize XOR #1149
-
Topics: Given two positive integers
Note that Return the integer The number of set bits of an integer is the number of Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The idea is to manipulate the bits of Steps:
Let's implement this solution in PHP: 2429. Minimize XOR <?php
/**
* @param Integer $num1
* @param Integer $num2
* @return Integer
*/
function minimizeXor($num1, $num2) {
// Count the number of set bits in num2
$setBitsCount = countSetBits($num2);
// Create the result x
$x = 0;
// Preserve the most significant bits from num1
for ($i = 31; $i >= 0 && $setBitsCount > 0; $i--) {
if (($num1 & (1 << $i)) != 0) {
$x |= (1 << $i);
$setBitsCount--;
}
}
// If there are still bits to set, set them from the least significant bit
for ($i = 0; $i <= 31 && $setBitsCount > 0; $i++) {
if (($x & (1 << $i)) == 0) {
$x |= (1 << $i);
$setBitsCount--;
}
}
return $x;
}
/**
* Helper function to count the number of set bits in a number
*
* @param $num
* @return int
*/
function countSetBits($num) {
$count = 0;
while ($num > 0) {
$count += $num & 1;
$num >>= 1;
}
return $count;
}
// Test cases
echo minimizeXor(3, 5) . "\n"; // Output: 3
echo minimizeXor(1, 12) . "\n"; // Output: 3
?> Explanation:
Complexity:
Example Walkthrough:Example 1:
Example 2:
This ensures the correct and efficient computation of |
Beta Was this translation helpful? Give feedback.
The idea is to manipulate the bits of
num1
and match the number of set bits (1
s) innum2
while minimizing the XOR result. Here's the step-by-step approach:Steps:
Count the Set Bits in
num2
:1
s in the binary representation ofnum2
. Let's call thissetBitsCount
.Create a Result Number
x
:x = 0
.num1
, preserve the1
s in the most significant positions that matchsetBitsCount
.1
s innum1
, add extra1
s starting from the least significant bit.Optimize XOR Result:
x
with the most significant1
s ofnum1
, the XOR value will be minimized.Return the Result: