大数相加(go实现)

2019-06-25  本文已影响0人  pengtoxen
package main

import "fmt"

//初始化数据
var a = []int{0, 2, 6, 1, 8, 9, 1, 0}
var b = []int{2, 2, 8, 1, 8, 9, 5, 0}
var r = make([]int, len(a))

//大数相加
func bigAdd(a []int, b []int, r []int) []int {
    for i := 0; i < len(a)-1; i++ {
        if a[i]+b[i] < 10 {
            r[i] = r[i] + a[i] + b[i]
        } else {
            r[i] = r[i] + (a[i]+b[i])%10
            r[i+1]++
        }
    }
    return r
}

func main() {
    ret := bigAdd(a, b, r)
    fmt.Println(ret)
}

输出

[2 4 4 3 6 9 7 0]
上一篇 下一篇

猜你喜欢

热点阅读