-
Notifications
You must be signed in to change notification settings - Fork 5
/
add_binary.go
76 lines (67 loc) · 1.24 KB
/
add_binary.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import "strings"
func addBinary(a string, b string) string {
memory := false
if len(b) < len(a) {
a, b = b, a
}
m := len(a)
n := len(b)
answer := []string{}
for i := m - 1; i >= 0; i-- {
x := string(a[i])
y := string(b[(n-m)+i])
if x == "1" && y == "1" {
if memory {
answer = append(answer, "1")
} else {
answer = append(answer, "0")
memory = true
}
} else if x == "1" || y == "1" {
if memory {
answer = append(answer, "0")
} else {
answer = append(answer, "1")
}
} else {
if memory {
answer = append(answer, "1")
memory = false
} else {
answer = append(answer, "0")
}
}
}
for i := n - m - 1; i >= 0; i-- {
x := string(b[i])
if x == "1" {
if memory {
answer = append(answer, "0")
} else {
answer = append(answer, "1")
}
} else if x == "0" {
if memory {
answer = append(answer, "1")
memory = false
} else {
answer = append(answer, "0")
}
}
}
if memory {
answer = append(answer, "1")
}
return strings.Join(reverse(answer), "")
}
func reverse(array []string) []string {
left := 0
right := len(array) - 1
for left < right {
array[left], array[right] = array[right], array[left]
left++
right--
}
return array
}