---
# System prepended metadata

title: 2429. Minimize XOR

---


# 2429. Minimize XOR
[2429. Minimize XOR](https://leetcode.com/problems/minimize-xor) (<font color="#FFB800"> Medium</font> 通過率: 53.2%)



## 限制條件
<ul>
<li>1 <= num1, num2 <= 10^9</li>
</ul>




### 解法 1
使用了一個不好 debug 的方法，先用 vector 把數字轉成 bool 的陣列，然後去計算 num2 有幾個1，接著先把 num1 原有的位元內把所有的0轉換成1，接著再慢慢從最小位補一補到 num2 個 1

- 時間複雜度: O(n)
- 空間複雜度: O(n)

```cpp!=
class Solution {
public:
    // Convert number to binary vector
    vector<int> numToVec(int num) {
        vector<int> record(31, 0);
        for (int i = 30; i >= 0; i--) {
            record[i] = num & 1;
            num >>= 1;
        }
        return record;
    }

    int minimizeXor(int num1, int num2) {
        // Get binary vector representations
        vector<int> num1Vec = numToVec(num1);
        vector<int> num2Vec = numToVec(num2);
        vector<int> resultVec(31, 0);

        // Count the number of set bits in num2
        int num2sb = 0;
        for (auto& num : num2Vec) {
            num2sb += num;
        }

        // Assign bits from num1 to result
        for (int i = 0; i < 31; i++) {
            if (num1Vec[i] == 1 && num2sb > 0) {
                resultVec[i] = 1;
                num2sb--;
            }
        }

        // Assign remaining bits if necessary
        for (int i = 0; i < 31; i++) {
            if (num2sb == 0)
                break;
            if (resultVec[30 - i] == 0) {
                resultVec[30 - i] = 1;
                num2sb--;
            }
        }

        // Convert binary vector back to integer
        int result = 0;
        for (int i = 0; i < 31; i++) {
            result |= (resultVec[i] << (30 - i));
        }

        return result;
    }
};

```
