题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
package main import ( "fmt" "strconv" ) func stringAdd(s1 string, s2 string) string { var s string var step int idx1, idx2 := len(s1)-1, len(s2)-1 for idx1 >= 0 || idx2 >= 0 { var n1 int var n2 int if idx1 >= 0 { n1 = int(s1[idx1] - '0') idx1-- } if idx2 >= 0 { n2 = int(s2[idx2] - '0') idx2-- } sum := (n1 + n2 + step) % 10 step = (n1 + n2 + step) / 10 s = strconv.Itoa(sum) + s } if step == 1 { s = strconv.Itoa(step) + s } return s } func main() { var s1 string var s2 string fmt.Scan(&s1, &s2) fmt.Println(stringAdd(s1, s2)) }
// 本题输入两个字符串,所以采用:fmt.Scan(&s1, &s2)