RainX_69

MINIMIZE XOR

Dec 17th, 2022
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | Source Code | 0 0
  1. /*
  2.  
  3. Given two positive integers num1 and num2, find the positive integer x such that:
  4.  
  5. x has the same number of set bits as num2, and
  6. The value x XOR num1 is minimal.
  7. Note that XOR is the bitwise XOR operation.
  8.  
  9. Return the integer x. The test cases are generated such that x is uniquely determined.
  10.  
  11. The number of set bits of an integer is the number of 1's in its binary representation.
  12.  
  13.  
  14.  
  15. Example 1:
  16.  
  17. Input: num1 = 3, num2 = 5
  18. Output: 3
  19. Explanation:
  20. The binary representations of num1 and num2 are 0011 and 0101, respectively.
  21. The integer 3 has the same number of set bits as num2, and the value 3 XOR 3 = 0 is minimal.
  22. Example 2:
  23.  
  24. Input: num1 = 1, num2 = 12
  25. Output: 3
  26. Explanation:
  27. The binary representations of num1 and num2 are 0001 and 1100, respectively.
  28. The integer 3 has the same number of set bits as num2, and the value 3 XOR 1 = 2 is minimal.
  29.  
  30.  
  31. Constraints:
  32.  
  33. 1 <= num1, num2 <= 10^9
  34.  
  35. */
  36.  
  37. class Solution {
  38. public:
  39.     int minimizeXor(int num1, int num2) {
  40.         int count=__builtin_popcount(num2);
  41.         int res=0;
  42.         for(int i=31;i>=0 && count>0;i--){   /* 2^31 to 2^0, first try to set bits in res which are already set in num1 at highest powers of 1. Because when finally res and num1 will xor, 1 and 1 will give 0, so we try to cancel out the largest powers positions */
  43.             int bit_state=(num1 >> i) & 1;
  44.             if(bit_state==1){
  45.                 res=res | (1 << i);
  46.                 count--;
  47.             }
  48.         }
  49.        
  50.         for(int i=0;i<32 && count>0;i++){   // 2^0 to 2^31, if you still have some count left, turn on bits of small powers of 2, so start from power 0
  51.             int bit_state=(res >> i) & 1;
  52.             if(bit_state==1){
  53.                 continue;
  54.             }
  55.             res=res | (1 << i);
  56.             count--;
  57.         }
  58.         return res;
  59.     }
  60. };
Tags: minimise Xor
Advertisement
Add Comment
Please, Sign In to add comment