Skip to content

Commit 44542c5

Browse files
committed
67. Add Binary
1 parent ea970a1 commit 44542c5

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

add-binary/ main.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package leecode
2+
3+
func addBinary(a string, b string) string {
4+
var ret []rune
5+
var sum rune
6+
ar := []rune(a)
7+
br := []rune(b)
8+
i := len(ar) - 1
9+
j := len(br) - 1
10+
for i >= 0 || j >= 0 || sum == 1 {
11+
if i >= 0 {
12+
sum = sum + ar[i] - '0'
13+
} else {
14+
sum = sum + 0
15+
}
16+
if j >= 0 {
17+
sum = sum + br[j] - '0'
18+
} else {
19+
sum = sum + 0
20+
}
21+
// If current digit sum is 1 or 3, add 1 to result
22+
ret = append([]rune{rune(sum%2 + '0')}, ret...)
23+
sum = sum / 2
24+
i--
25+
j--
26+
}
27+
return string(ret)
28+
}

add-binary/Readme.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# 67. Add Binary
2+
3+
Source: https://leetcode.com/problems/add-binary/description/

add-binary/main_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package leecode
2+
3+
import "testing"
4+
5+
func TestAddBinary(t *testing.T) {
6+
testcases := []struct {
7+
A string
8+
B string
9+
Expected string
10+
}{
11+
{
12+
A: "11",
13+
B: "1",
14+
Expected: "100",
15+
},
16+
{
17+
A: "1010",
18+
B: "1011",
19+
Expected: "10101",
20+
},
21+
}
22+
23+
for _, tc := range testcases {
24+
actual := addBinary(tc.A, tc.B)
25+
if actual != tc.Expected {
26+
t.Errorf("not equal. Expected: %s, when get %s", tc.Expected, actual)
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)