-
Notifications
You must be signed in to change notification settings - Fork 0
/
67.go
107 lines (84 loc) · 1.49 KB
/
67.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
# ------------------------------ #
# #
# version 0.0.1 #
# #
# Aleksiej Ostrowski, 2022 #
# #
# https://aleksiej.com #
# #
# ------------------------------ #
*/
package main
import (
"fmt"
)
func charbin2byte(char byte) byte {
switch char {
case 48:
return 0
case 49:
return 1
}
return 255
}
func byte2charbin(b byte) byte {
switch b {
case 0:
return 48
case 1:
return 49
}
return 255
}
func addBinary(a string, b string) string {
overflow := 0
len_a := len(a)
len_b := len(b)
ind_a := len_a - 1
ind_b := len_b - 1
var res []rune
if len_a > len_b {
res = make([]rune, len_a)
} else {
res = make([]rune, len_b)
}
len_res := len(res)
ind_res := len_res - 1
for {
new_var := overflow
if ind_a >= 0 {
new_var += int(charbin2byte(a[ind_a]))
ind_a -= 1
}
if ind_b >= 0 {
new_var += int(charbin2byte(b[ind_b]))
ind_b -= 1
}
overflow = 0
switch new_var {
case 0, 1:
res[ind_res] = rune(byte2charbin(byte(new_var)))
case 2:
res[ind_res] = rune(byte2charbin(0))
overflow += 1
case 3:
res[ind_res] = rune(byte2charbin(1))
overflow += 1
}
if (ind_a < 0) && (ind_b < 0) {
break
}
ind_res -= 1
}
if overflow > 0 {
res = append([]rune{49}, res...)
}
return string(res)
}
func main() {
a := "10111"
b := "1"
fmt.Println(addBinary(a, b))
fmt.Println("ok")
}