-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadd-binary.go
More file actions
99 lines (72 loc) · 1.13 KB
/
add-binary.go
File metadata and controls
99 lines (72 loc) · 1.13 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
95
96
97
98
99
package main
import (
"fmt"
"strings"
"strconv"
)
func addBinary(a string, b string) string {
if a == "0" {
return b
}
if b == "0" {
return a
}
al := len(a)
bl := len(b)
l := 0
if al >= bl {
l = al
} else {
l = bl
}
aList := strings.Split(a, "")
bList := strings.Split(b, "")
list := []string{}
lab := false
for i:=0; i<=l; i++ {
aNumber := 0
bNumber := 0
if i<len(aList) {
aNumber,_ = strconv.Atoi(aList[al - 1 - i])
}
if i<len(bList) {
bNumber,_ = strconv.Atoi(bList[bl - 1 - i])
}
if i== l {
if lab {
list = append(list,"1")
}
break
}
sum := aNumber + bNumber
if sum >= 2 {
if lab {
list = append(list,"1")
}else {
list = append(list,"0")
lab = true
}
}else {
if lab {
sum = sum + 1
}
if sum >= 2 {
list = append(list,"0")
lab = true
}else {
s := strconv.Itoa(sum)
list = append(list,s)
lab = false
}
}
}
str := ""
for j:=len(list) -1; j>=0; j-- {
str += list[j]
}
return str
}
func main() {
fmt.Println(addBinary("100", "110010")) // 100
fmt.Println(addBinary("1010", "1011")) // 10101
}