题目
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
- The length of both num1 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
解题思路
从低位往上加,注意进位
边界条件比较多,写个测试会好很多
代码
addStrings.go
package _415_Add_Strings
import (
"strconv"
)
func AddStrings(num1 string, num2 string) string {
len1 := len(num1)
len2 := len(num2)
var ret string
var carry int
var digit int
for i, j := len1, len2; i > 0 || j > 0 || carry > 0; {
digit = carry
if i > 0 {
i--
digit += int(num1[i] - '0')
}
if j > 0 {
j--
digit += int(num2[j] - '0')
}
if digit > 9 {
carry = 1
} else {
carry = 0
}
ret = strconv.Itoa(digit % 10) + ret
}
return ret
}
测试
addStrings_test.go
package _415_Add_Strings
import "testing"
func TestAddStrings(t *testing.T) {
var tests = []struct{
num1 string
num2 string
output string
}{
{"0", "0", "0"},
{"1", "2", "3"},
{"123", "12", "135"},
}
for _, v := range tests {
ret := AddStrings(v.num1, v.num2)
if ret == v.output {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", v.output, ret)
}
}
}