-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3226-NumberOfBitChangesToMakeTwoIntegersEqual.go
More file actions
94 lines (81 loc) · 2.59 KB
/
3226-NumberOfBitChangesToMakeTwoIntegersEqual.go
File metadata and controls
94 lines (81 loc) · 2.59 KB
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
89
90
91
92
93
94
package main
// 3226. Number of Bit Changes to Make Two Integers Equal
// You are given two positive integers n and k.
// You can choose any bit in the binary representation of n that is equal to 1 and change it to 0.
// Return the number of changes needed to make n equal to k. If it is impossible, return -1.
// Example 1:
// Input: n = 13, k = 4
// Output: 2
// Explanation:
// Initially, the binary representations of n and k are n = (1101)2 and k = (0100)2.
// We can change the first and fourth bits of n. The resulting integer is n = (0100)2 = k.
// Example 2:
// Input: n = 21, k = 21
// Output: 0
// Explanation:
// n and k are already equal, so no changes are needed.
// Example 3:
// Input: n = 14, k = 13
// Output: -1
// Explanation:
// It is not possible to make n equal to k.
// Constraints:
// 1 <= n, k <= 10^6
import "fmt"
import "math/bits"
func minChanges(n int, k int) int {
res := 0
for n > 0 || k > 0 {
nmod, kmod := n % 2, k % 2
if nmod == kmod {
n, k = n / 2, k / 2
continue
}
if nmod == 0 && kmod == 1 { return -1 }
n, k = n / 2, k / 2
res++
}
return res
}
func minChanges1(n int, k int) int {
if n & k == k {
return bits.OnesCount(uint(n ^ k))
}
return -1
}
func main() {
// Example 1:
// Input: n = 13, k = 4
// Output: 2
// Explanation:
// Initially, the binary representations of n and k are n = (1101)2 and k = (0100)2.
// We can change the first and fourth bits of n. The resulting integer is n = (0100)2 = k.
fmt.Println(minChanges(13, 4)) // 2
// Example 2:
// Input: n = 21, k = 21
// Output: 0
// Explanation:
// n and k are already equal, so no changes are needed.
fmt.Println(minChanges(21, 21)) // 0
// Example 3:
// Input: n = 14, k = 13
// Output: -1
// Explanation:
// It is not possible to make n equal to k.
fmt.Println(minChanges(14, 13)) // -1
fmt.Println(minChanges(1, 1)) // 0
fmt.Println(minChanges(100000, 100000)) // 0
fmt.Println(minChanges(1, 100000)) // -1
fmt.Println(minChanges(100000, 1)) // -1
fmt.Println(minChanges(1, 99999)) // -1
fmt.Println(minChanges(99999, 1)) // 9
fmt.Println(minChanges1(13, 4)) // 2
fmt.Println(minChanges1(21, 21)) // 0
fmt.Println(minChanges1(14, 13)) // -1
fmt.Println(minChanges1(1, 1)) // 0
fmt.Println(minChanges1(100000, 100000)) // 0
fmt.Println(minChanges1(1, 100000)) // -1
fmt.Println(minChanges1(100000, 1)) // -1
fmt.Println(minChanges1(1, 99999)) // -1
fmt.Println(minChanges1(99999, 1)) // 9
}