Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 79d372d

Browse files
author
Sandy
authored
Merge pull request #104 from openset/develop
Add: add_binary
2 parents aa18655 + 7962a2f commit 79d372d

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

‎problems/add-binary/add_binary.go‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,22 @@
11
package add_binary
2+
3+
func addBinary(a string, b string) string {
4+
i, j := len(a)-1, len(b)-1
5+
var carry byte = '0'
6+
var bs []byte
7+
for i >= 0 || j >= 0 || carry != '0' {
8+
v := carry
9+
if i >= 0 {
10+
v += a[i] - '0'
11+
i--
12+
}
13+
if j >= 0 {
14+
v += b[j] - '0'
15+
j--
16+
}
17+
carry = '0' + (v-'0')/2
18+
v = '0' + (v-'0')%2
19+
bs = append([]byte{v}, bs...)
20+
}
21+
return string(bs)
22+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
11
package add_binary
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
a string
7+
b string
8+
expected string
9+
}
10+
11+
func TestAddBinary(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
a: "11",
15+
b: "1",
16+
expected: "100",
17+
},
18+
{
19+
a: "1010",
20+
b: "1011",
21+
expected: "10101",
22+
},
23+
{
24+
a: "111",
25+
b: "111",
26+
expected: "1110",
27+
},
28+
}
29+
for _, tc := range tests {
30+
output := addBinary(tc.a, tc.b)
31+
if output != tc.expected {
32+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.a, tc.b, output, tc.expected)
33+
}
34+
}
35+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /