题目描述
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
(给两个非负数字符串——num1和num2,返回两个数的乘积,也是字符串形式)
Example 1:
Input: num1 = “2”, num2 = “3”
Output: “6”
Example 2:
Input: num1 = “123”, num2 = “456”
Output: “56088”
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits 0-9. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
题目分析
题目中要求不能把字符串直接换成数字相乘,我们可以考虑使用我们人为算乘法的方式,两个数的某两位对应相乘,然后还要考虑到进位之类的操作。
代码示例
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var multiply = function(num1, num2) {
if(num1=='0'||num2=='0') return '0'
var len1 = num1.length
var len2 = num2.length
var res = new Array(len1+len2) // 存储结果中的每一位数字
for(var i=0;i<res.length;i++){
res[i] = 0 // 每一位先置为0
}
var cur = 0
for(var i=len1-1;i>=0;i--){
for(var j=len2-1;j>=0;j--){
// num1的第i位乘上num2的第j位,cur对应乘法所得的结果放在res中的第几位
cur = i+j+1
res[cur] += parseInt(num1[i]) * parseInt(num2[j])
// 如果相乘的数大于10,则进行进位操作
if(res[cur]>=10){
res[cur-1] += Math.floor(res[cur]/10)
res[cur] = res[cur] % 10
}
}
}
var ind = 0
while(ind<res.length && res[ind]=='0'){
res[ind] = ''
ind++
}
return res.join('')
};