給定兩個非常大的正整數A和B,位數在50至100之間。求C=A+B;
輸入:
因爲A和B很大,從高位到低位,以字符串的形式輸入兩行數字A和B。A和B的位數在50至100之間。
輸出:
以字符串形式,輸出一行,表示A和B的和。
樣例輸入:
11111111111111111111111111111111111
22222222222222222222222222222222222
樣例輸出:
33333333333333333333333333333333333
代碼實現:
package huawei
import (
"bytes"
"fmt"
"strconv"
"strings"
)
func Test2Base() {
s := add("91111111111111111111111111111111111", "122222222222222222222222222222222222")
fmt.Println(s)
}
func add(a string, b string) string {
//位數較少的,高位補0
if len(a) < len(b) {
a = strings.Repeat("0", len(b)-len(a)) + a
} else if len(a) > len(b) {
b = strings.Repeat("0", len(a)-len(b)) + b
}
strLen := len(a)
//保存結果的數組,從低位到高位進行保存
nums := make([]uint8, strLen)
//從低位到高位開始遍歷a,b
addOne := false
for i := 0; i < strLen; i++ {
num_a := a[strLen-i-1] - '0'
num_b := b[strLen-i-1] - '0'
sum := num_a + num_b
if addOne {
sum++
}
if sum > 9 {
//進位
sum -= 10
addOne = true
} else {
addOne = false
}
nums[i] = sum
}
result := convertToString(nums)
//進位,最前面補1
if addOne {
result = "1" + result
}
return result
}
func convertToString(nums []uint8) string {
var b bytes.Buffer
for i := len(nums) - 1; i >= 0; i-- {
b.WriteString(strconv.Itoa(int(nums[i])))
}
return b.String()
}