Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Given two positive integers num1 and num2, find the positive integer x such that:
- x has the same number of set bits as num2, and
- The value x XOR num1 is minimal.
- 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:
- 1 <= num1, num2 <= 10^9
- */
- class Solution {
- public:
- int minimizeXor(int num1, int num2) {
- int count=__builtin_popcount(num2);
- int res=0;
- 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 */
- int bit_state=(num1 >> i) & 1;
- if(bit_state==1){
- res=res | (1 << i);
- count--;
- }
- }
- 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
- int bit_state=(res >> i) & 1;
- if(bit_state==1){
- continue;
- }
- res=res | (1 << i);
- count--;
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment