-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution868.go
54 lines (45 loc) · 918 Bytes
/
solution868.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
package solution868
// ============================================================================
// 868. Binary Gap
// URL: https://leetcode.com/problems/binary-gap/
// ============================================================================
/*
goos: linux
goarch: amd64
pkg: GoLeetCode/solutions/868---Binary-Gap
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
BenchmarkBinaryGap
BenchmarkBinaryGap-24 9231778 129.9 ns/op 0 B/op 0 allocs/op
PASS
*/
func binaryGap(n int) int {
var a, b, m int
isOne := func(pos int) bool {
if val := n & (1 << pos); val > 0 {
return true
}
return false
}
a = 63
b = a - 1
for {
switch {
case isOne(a) && isOne(b):
m = max(m, a-b)
a = b
b--
case isOne(a) && !isOne(b):
b--
case !isOne(a) && !isOne(b):
b--
a--
case !isOne(a) && isOne(b):
a = b
b--
}
if b < 0 {
break
}
}
return m
}