-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path67.Add-Binary.go
72 lines (63 loc) · 1.22 KB
/
67.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
// https://leetcode.com/problems/add-binary/
//
// algorithms
// Easy (36.71%)
// Total Accepted: 252,250
// Total Submissions: 687,192
// beats 100.0% of golang submissions
package leetcode
import (
"bytes"
"strconv"
)
func addBinary(a string, b string) string {
a, b = reverse(a), reverse(b)
aLen, bLen := len(a), len(b)
carry := 0
res := bytes.NewBufferString("")
for i := 0; i < min(aLen, bLen); i++ {
cntBit := int((a[i]-48)+(b[i]-48)) + carry
carry = cntBit / 2
cntBit = cntBit % 2
res.WriteString(strconv.Itoa(cntBit))
}
if aLen != bLen {
idx := bLen
length := aLen
if aLen < bLen {
a = b
idx = aLen
length = bLen
}
for i := idx; i < length; i++ {
cntBit := int((a[i] - 48)) + carry
carry = cntBit / 2
cntBit = cntBit % 2
res.WriteString(strconv.Itoa(cntBit))
if carry == 0 {
res.WriteString(a[i+1:])
break
}
}
if carry == 1 {
res.WriteString("1")
}
} else if carry == 1 {
res.WriteString("1")
}
return reverse(res.String())
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func reverse(s string) string {
length := len(s)
res := bytes.NewBufferString("")
for i := length - 1; i >= 0; i-- {
res.WriteByte(s[i])
}
return res.String()
}