Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3" Output: "6"
Example 2:
Input: num1 = "123", num2 = "456" Output: "56088"
Constraints:
1 <= num1.length, num2.length <= 200
num1
andnum2
consist of digits only.- Both
num1
andnum2
do not contain any leading zero, except the number0
itself.
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
- 用数组模拟乘法。创建一个数组长度为
len(num1) + len(num2)
的数组用于存储乘积。对于任意0 ≤ i < len(num1)
,0 ≤ j < len(num2)
,num1[i] * num2[j]
的结果位于tmp[i+j+1]
,如果tmp[i+j+1]≥10
,则将进位部分加到tmp[i+j]
。最后,将数组tmp
转成字符串,如果最高位是 0 则舍弃最高位。
package leetcode funcmultiply(num1string, num2string) string { ifnum1=="0"||num2=="0" { return"0" } b1, b2, tmp:= []byte(num1), []byte(num2), make([]int, len(num1)+len(num2)) fori:=0; i<len(b1); i++ { forj:=0; j<len(b2); j++ { tmp[i+j+1] +=int(b1[i]-'0') *int(b2[j]-'0') } } fori:=len(tmp) -1; i>0; i-- { tmp[i-1] +=tmp[i] /10tmp[i] =tmp[i] %10 } iftmp[0] ==0 { tmp=tmp[1:] } res:=make([]byte, len(tmp)) fori:=0; i<len(tmp); i++ { res[i] ='0'+byte(tmp[i]) } returnstring(res) }