以字符串的形式读入两个数字,编写一个函数计算它们的和,以字符串形式返回。
数据范围:len(s),len(t) le 100000len(s),len(t)≤100000,字符串仅由'0'~‘9’构成
要求:时间复杂度 O(n)O(n)
package main
import "fmt"
func solve(s string, t string) string {
anum := len(s) - 1
bnum := len(t) - 1
big := anum
if big < bnum {
big = bnum
}
sumstring := make([]byte, big+2)
//fmt.Println(len(sumstring))
var sum, sy, p uint8
p = 0
i := 0
//fmt.Println(sum)
for ; anum >= 0 && bnum >= 0; i++ {
sum = t[bnum] - '0' + s[anum] - '0' + p
p = 0
sy = sum % 10
if sum >= 10 {
p = 1
}
sumstring[i] = sy
bnum--
anum--
//fmt.Println("第一个for:", sum, bnum, anum)
}
//for j := len(sumstring) - 1; j >= 0; j-- {
// fmt.Print(sumstring[j])
//}
//fmt.Println()
if bnum != -1 {
for ; bnum >= 0; bnum-- {
lm := t[bnum] - '0' + p
sumstring[i] = (lm) % 10
p = 0
if lm >= 10 {
p = 1
}
i++
}
} else if anum != -1 {
for ; anum >= 0; anum-- {
//fmt.Print(s[anum] - '0' + p)
//fmt.Println()
ll := s[anum] - '0' + p
sumstring[i] = (ll) % 10
p = 0
if ll > 9 {
//fmt.Println("大于10了")
p = 1
}
i++
}
//fmt.Print(anum, p, i)
//fmt.Println()
}
var pi int = 0
if p > 0 {
sumstring[i] = 1
pi = 1
}
var scv string
//fmt.Println(len(sumstring), pi)
for i = len(sumstring) - 2 + pi; i >= 0; i-- {
//fmt.Print(sumstring[i])
scv = scv + fmt.Sprintf("%d", sumstring[i])
}
//fmt.Printf("%s", scv)
return scv
}
func main() {
fmt.Println(solve("123", "98"))
}