-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminimum-array-end.go
60 lines (49 loc) · 961 Bytes
/
minimum-array-end.go
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
package main
// source: https://leetcode.com/problems/minimum-array-end/
// [n]int, for each element nums[i] < nums[i+1] and ANDing all elements equals x
// return min possible value for nums[n-1] last element
func getBits(x int) []int {
bits := make([]int, 0, 32)
for x > 0 {
bits = append(bits, x&1)
x >>= 1
}
return bits
}
func minEnd(n int, x int) int64 {
nb := getBits(n - 1)
xb := getBits(x)
ni := 0
// add n to x with saving x's bits unchanged
for xi := 0; xi < len(xb) && ni < len(nb); xi++ {
if xb[xi] == 0 {
xb[xi] = nb[ni]
ni++
}
}
// add remaining
if ni < len(nb) {
xb = append(xb, nb[ni:]...)
}
var ans int64
for i := len(xb) - 1; i >= 0; i-- {
ans <<= 1
ans += int64(xb[i])
}
return ans
}
func minEnd_TLE(n int, x int) int64 {
var ans int64 = 0
x64 := int64(x)
for c := int64(x); n > 0; c++ {
if c&x64 == x64 {
n--
ans = c
}
}
return ans
}
func main() {
minEnd(3, 4)
minEnd(2, 7)
}