Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit e983cea

Browse files
aQuaaQua
aQua
authored and
aQua
committed
67 finish
1 parent f7ff0c8 commit e983cea

File tree

3 files changed

+146
-0
lines changed

3 files changed

+146
-0
lines changed

Algorithms/0067.add-binary/README.md

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# [67. Add Binary](https://leetcode.com/problems/add-binary/)
2+
3+
## 题目
4+
Given two binary strings, return their sum (also a binary string).
5+
6+
```
7+
For example,
8+
a = "11"
9+
b = "1"
10+
Return "100".
11+
```
12+
## 解题思路
13+
14+
见程序注释
+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package Problem0067
2+
3+
func addBinary(a string, b string) string {
4+
if len(a) < len(b) {
5+
a, b = b, a
6+
}
7+
l := len(a)
8+
9+
isA := trans(a, l)
10+
isB := trans(b, l)
11+
12+
return makeString(add(isA, isB))
13+
}
14+
15+
func trans(s string, l int) []int {
16+
res := make([]int, l)
17+
ls := len(s)
18+
for i, b := range s {
19+
res[l-ls+i] = int(b - '0')
20+
}
21+
22+
return res
23+
}
24+
25+
func add(a, b []int) []int {
26+
l := len(a) + 1
27+
res := make([]int, l)
28+
for i := l - 1; i >= 1; i-- {
29+
temp := res[i] + a[i-1] + b[i-1]
30+
res[i] = temp % 2
31+
res[i-1] = temp / 2
32+
}
33+
34+
i := 0
35+
36+
// i < l-1 而不是 l 的原因是
37+
// "" + "" == "0"
38+
// 需要保留最后一个 '0'
39+
for i < l-1 && res[i] == 0 {
40+
i++
41+
}
42+
43+
return res[i:]
44+
}
45+
46+
func makeString(nums []int) string {
47+
bytes := make([]byte, len(nums))
48+
for i := range bytes {
49+
bytes[i] = byte(nums[i]) + '0'
50+
}
51+
52+
return string(bytes)
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package Problem0067
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type question struct {
11+
para
12+
ans
13+
}
14+
15+
// para 是参数
16+
type para struct {
17+
a string
18+
b string
19+
}
20+
21+
// ans 是答案
22+
type ans struct {
23+
one string
24+
}
25+
26+
func Test_Problem0067(t *testing.T) {
27+
ast := assert.New(t)
28+
29+
qs := []question{
30+
31+
question{
32+
para{
33+
"11",
34+
"1",
35+
},
36+
ans{
37+
"100",
38+
},
39+
},
40+
41+
question{
42+
para{
43+
"001",
44+
"000",
45+
},
46+
ans{
47+
"1",
48+
},
49+
},
50+
51+
question{
52+
para{
53+
"",
54+
"",
55+
},
56+
ans{
57+
"0",
58+
},
59+
},
60+
61+
question{
62+
para{
63+
"",
64+
"1",
65+
},
66+
ans{
67+
"1",
68+
},
69+
},
70+
// 如需多个测试,可以复制上方元素。
71+
}
72+
73+
for _, q := range qs {
74+
a, p := q.ans, q.para
75+
fmt.Printf("~~%v~~\n", p)
76+
77+
ast.Equal(a.one, addBinary(p.a, p.b), "输入:%v", p)
78+
}
79+
}

0 commit comments

Comments
 (0)