2429. Minimize XOR

Difficulty:
Related Topics:
    Similar Questions:

    Problem

    Given two positive integers num1 and num2, find the integer x such that:

    Note that XOR is the bitwise XOR operation.

    Return **the integer **x. The test cases are generated such that x is uniquely determined.

    The number of set bits of an integer is the number of 1's in its binary representation.

      Example 1:

    Input: num1 = 3, num2 = 5
    Output: 3
    Explanation:
    The binary representations of num1 and num2 are 0011 and 0101, respectively.
    The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal.
    

    Example 2:

    Input: num1 = 1, num2 = 12
    Output: 3
    Explanation:
    The binary representations of num1 and num2 are 0001 and 1100, respectively.
    The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal.
    

      Constraints:

    Solution (Java)

    class Solution {
        public int minimizeXor(int num1, int num2) {
    
            int []arr = new int[32];
    
            int count = 0;
            for(int i = 0; i < 32; i++){
                if((num2 & (1 << i)) != 0){
                    count++;
                }
            }
    
            for(int i = 31; i >= 0; i--){
                if((num1 & (1 << i)) != 0 && count > 0){
                    arr[i] = 1;
                    count--;
                }
            }
    
          if(count > 0){
                for(int i = 0; i < 32 && count > 0; i++){
                    if(arr[i] != 1){
                        arr[i] = 1;
                        count--;
                    }
                }
            }
    
            StringBuilder str = new StringBuilder();
            for(int i = 0; i < 32; i++){
                str.insert(0, arr[i]);
            }
    
            return Integer.parseInt(str.toString(), 2);
        }
    }
    

    Explain:

    nope.

    Complexity: