Skip to content

Commit e5d750a

Browse files
author
Shuo
authored
Merge pull request #654 from openset/develop
Add: Add Strings
2 parents 5cde1e5 + 92cf8ea commit e5d750a

File tree

4 files changed

+72
-16
lines changed

4 files changed

+72
-16
lines changed

problems/add-binary/add_binary.go

+11-13
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
1-
package add_binary
1+
package problem_67
22

33
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' {
4+
ans, l1, l2, carry := "", len(a)-1, len(b)-1, byte('0')
5+
for l1 >= 0 || l2 >= 0 || carry != '0' {
86
v := carry
9-
if i >= 0 {
10-
v += a[i] - '0'
11-
i--
7+
if l1 >= 0 {
8+
v += a[l1] - '0'
9+
l1--
1210
}
13-
if j >= 0 {
14-
v += b[j] - '0'
15-
j--
11+
if l2 >= 0 {
12+
v += b[l2] - '0'
13+
l2--
1614
}
1715
carry = '0' + (v-'0')/2
1816
v = '0' + (v-'0')%2
19-
bs = append([]byte{v}, bs...)
17+
ans = string(v) + ans
2018
}
21-
return string(bs)
19+
return ans
2220
}

problems/add-binary/add_binary_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package add_binary
1+
package problem_67
22

33
import "testing"
44

problems/add-strings/add_strings.go

+20-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,20 @@
1-
package add_strings
1+
package problem_415
2+
3+
func addStrings(num1 string, num2 string) string {
4+
ans, l1, l2, carry := "", len(num1)-1, len(num2)-1, byte('0')
5+
for l1 >= 0 || l2 >= 0 || carry != '0' {
6+
v := carry
7+
if l1 >= 0 {
8+
v += num1[l1] - '0'
9+
l1--
10+
}
11+
if l2 >= 0 {
12+
v += num2[l2] - '0'
13+
l2--
14+
}
15+
carry = '0' + (v-'0')/10
16+
v = '0' + (v-'0')%10
17+
ans = string(v) + ans
18+
}
19+
return ans
20+
}
+40-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,40 @@
1-
package add_strings
1+
package problem_415
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
num1 string
7+
num2 string
8+
expected string
9+
}
10+
11+
func TestAddStrings(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
num1: "0",
15+
num2: "0",
16+
expected: "0",
17+
},
18+
{
19+
num1: "1",
20+
num2: "2",
21+
expected: "3",
22+
},
23+
{
24+
num1: "9",
25+
num2: "9",
26+
expected: "18",
27+
},
28+
{
29+
num1: "100",
30+
num2: "999",
31+
expected: "1099",
32+
},
33+
}
34+
for _, tc := range tests {
35+
output := addStrings(tc.num1, tc.num2)
36+
if output != tc.expected {
37+
t.Fatalf("input: %v, output: %v, expected: %v", tc, output, tc.expected)
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)