Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created January 15, 2025 06:48
Show Gist options
  • Save Ifihan/3c499ba9cf70d6f57bb92999075f8733 to your computer and use it in GitHub Desktop.
Save Ifihan/3c499ba9cf70d6f57bb92999075f8733 to your computer and use it in GitHub Desktop.
Minimize XOR

Question

Approach

My approach was to construct (x) by considering the bits of num1 and num2. First, I counted the number of set bits in num2 using Python's bin(num2).count('1').

To minimize the XOR value, I prioritized aligning (x) with the bits of num1 where possible. Starting from the most significant bit, I iterated through all the bits of num1. Whenever I met a set bit (1) in num1 and still needed more set bits in (x), I copied that bit into (x). This helped (x) resemble num1, minimizing their XOR value.

If the required number of set bits was not achieved after aligning with num1, I switched to filling (x) with additional set bits from the least significant bit upward.

Finally, I returned (x).

Implementation

class Solution:
    def minimizeXor(self, num1: int, num2: int) -> int:
        set_bits_num2 = bin(num2).count('1')

        result = 0
        set_bits_added = 0

        for i in range(31, -1, -1):
            if (num1 & (1 << i)) != 0 and set_bits_added < set_bits_num2:
                result |= (1 << i)
                set_bits_added += 1

        for i in range(32):
            if set_bits_added >= set_bits_num2:
                break
            if (result & (1 << i)) == 0:
                result |= (1 << i)
                set_bits_added += 1

        return result

Complexities

  • Time: O(log M), where (M) is the value of num2.
  • Space: O(log M), for binary representation during set bit counting.
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment