大一上做过没做出来,一个月前写的不对,今天写出来了
// 模拟竖式运算 func multiply(num1 string, num2 string) string { var ans []byte // 结果,ans[i]是一个[0..9]的数,并且结果是逆序的 zeroCount := 0 for i := len(num2)-1; i >= 0; i-- { var tmp []byte // num2[i] * num1 的结果 // 填充"0", for k := 0; k < zeroCount; k++ { tmp = append(tmp, 0) } // 计算 num2[i] * num1 x := num2[i] - '0' var carry byte for j := len(num1)-1; j >= 0; j-- { y := num1[j] - '0' tmp = append(tmp, (x * y + carry) % 10) carry = (x * y + carry) / 10 } if carry != 0 { tmp = append(tmp, carry) } // ans += tmp if ans != nil { var carry, a, t byte for k := 0; (k < len(ans) || carry != 0) && k < len(tmp); k++ { t = tmp[k] if k < len(ans) {a = ans[k]} else {a = 0} tmp[k] = (t + a + carry) % 10 carry = (t + a + carry) / 10 } if carry != 0 { tmp = append(tmp, carry) } } ans = tmp zeroCount++ } allZero := true // 是否为0,特殊情况处理 // 反转 for L, R := 0, len(ans)-1; L <= R; L, R = L+1, R-1 { ans[L], ans[R] = ans[R] + '0', ans[L] + '0' if ans[L] != '0' || ans[R] != '0' { allZero = false } } if allZero { return "0" } return string(ans) }