Skip to content

Commit 076cf33

Browse files
committed
add_binary/
1 parent 8fc0197 commit 076cf33

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
5959
#### [64. minimum path sum](https://github.com/hitzzc/go-leetcode/tree/master/minimum_path_sum)
6060
#### [65. valid number](https://github.com/hitzzc/go-leetcode/tree/master/valid_number)
6161
#### [66. plus one](https://github.com/hitzzc/go-leetcode/tree/master/plus_one)
62+
#### [67. add binary](https://github.com/hitzzc/go-leetcode/tree/master/add_binary)
6263

6364

6465

add_binary/add_binary.go

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package add_binary
2+
3+
func addBinary(a string, b string) string {
4+
aBytes, bBytes := []byte(a), []byte(b)
5+
var carry, sum byte = '0', '0'
6+
short, long := aBytes, bBytes
7+
if len(aBytes) > len(bBytes) {
8+
short, long = bBytes, aBytes
9+
}
10+
newShort := make([]byte, len(long)-len(short))
11+
for i := range newShort {
12+
newShort[i] = '0'
13+
}
14+
newShort = append(newShort, short...)
15+
ret := make([]byte, len(long)+1)
16+
for i := len(long) - 1; i >= 0; i-- {
17+
sum, carry = add(newShort[i], long[i], carry)
18+
ret[i+1] = sum
19+
}
20+
if carry == '1' {
21+
ret[0] = carry
22+
} else {
23+
ret = ret[1:]
24+
}
25+
return string(ret)
26+
}
27+
28+
func add(a, b, c byte) (byte, byte) {
29+
if a == '0' && b == '0' {
30+
return c, '0'
31+
}
32+
if a == '1' && b == '1' {
33+
return c, '1'
34+
}
35+
if c == '1' {
36+
return '0', '1'
37+
}
38+
return '1', '0'
39+
}

add_binary/add_binary_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package add_binary
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestAddBinary(t *testing.T) {
8+
println(addBinary("010", "101"))
9+
}

0 commit comments

Comments
 (0)