2509 Minimize Xor
2509 Minimize Xor
Minimize XOR 
Given two positive integers num1 and num2, find the positive integer x such that:
1
2
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:
1
2
3
4
5
6
7
**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:
1
2
3
4
5
6
7
**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
1 <= num1, num2 <= 109
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
func minimizeXor(num1 int, num2 int) int {
count := 0
i := 0
for num2 != 0 {
i = num2 & 1
num2 = num2 >> 1
if i == 1 {
count += 1
}
}
res := make([]int,1)
num3 := num1
numof1 := 0
i = 0
for num3 != 0 {
i = num3 & 1
num3 = num3 >> 1
if i == 1{
numof1 += 1
}
}
//fmt.Println(countOfNum3)
diff1 := 0
diff2 := 0
if numof1 < count {
// more 1s available but less needed
// find first 0 from left and make it 1
diff2 = count - numof1
} else {
// less available but more needed
// skip diff 1s from left and then make rest equal
diff1 = numof1 - count
}
i = 0
for count > 0 {
fmt.Println(i, num1, res, count, diff1, diff2 )
i = num1 & 1
if i == 1 {
if diff1 > 0 { // skip diff1 number of 1s
res = append(res, 0)
diff1 --
} else {
res = append(res, 1)
//res = res | 1 // else attach 1
//res = res << 1
count --
}
} else {
if diff2 > 0 {
res = append(res, 1)
//res = res | 1 // if diff2 > 0 make first 0 from left and make it 1
//res = res << 1
diff2 --
count --
} else {
res = append(res, 0)
//res = res | 0 // else keep it zero
//res = res << 1
}
}
num1 = num1 >> 1
}
// reverse res
slices.Reverse(res)
fmt.Println(res[:len(res)-1])
res1 := 0
for j := 0 ; j < len(res)-1 ; j ++ {
res1 = res1 | res[j]
res1 = res1 << 1
}
//fmt.Println(res, num3 )
return res1 >> 1
}
This post is licensed under CC BY 4.0 by the author.