Skip to content

Commit 4e75430

Browse files
author
openset
committed
Add: Add Strings
1 parent bb28427 commit 4e75430

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

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)