链接
题目.
难度:
middle
解答:
其实就是各个数字相乘,把结果放到合适的位置,然后再按照各个位置进位。注意过程中要转换为int,byte容易溢出
package main
import (
"fmt"
"strings"
)
func multiply(num1 string, num2 string) string {
if num1 == "0" || num2 == "0" {
return "0"
}
num1Ints := make([]int, len(num1))
for i, j := 0, len(num1)-1; i < len(num1); i, j = i+1, j-1 {
num1Ints[j] = int(num1[i] - '0')
}
num2Ints := make([]int, len(num2))
for i, j := 0, len(num2)-1; i < len(num2); i, j = i+1, j-1 {
num2Ints[j] = int(num2[i] - '0')
}
resultInts := make([]int, len(num1)+len(num2))
for i := 0; i < len(num1Ints); i++ {
for j := 0; j < len(num2Ints); j++ {
resultInts[i+j] += num1Ints[i] * num2Ints[j]
}
}
for i := 0; i <= len(resultInts)-2; i++ {
resultInts[i+1] += resultInts[i] / 10
resultInts[i] = resultInts[i] % 10
}
if resultInts[len(resultInts)-1] == 0 {
resultInts = resultInts[:len(resultInts)-1]
}
builder := strings.Builder{}
for j := len(resultInts) - 1; j >= 0; j-- {
builder.WriteByte(byte(resultInts[j]) + '0')
}
return builder.String()
}
func main() {
fmt.Println(multiply("123", "456"))
}
复杂度分析
time
O(m*n)
space
O(m+n)
执行结果
执行用时 :0 ms, 在所有 golang 提交中击败了100.00%的用户
内存消耗 :2.4 MB, 在所有 golang 提交中击败了61.90%的用户