var multiply = function(num1, num2) {
const left = '0'.charCodeAt(0);
// console.log("left:"+left);
// 首先将字符串用 charCodeAt 转换成对应的数字。
// num1Arr 取较短的数字, num2Arr 取较长的数字,用 num1Arr 去分别乘 num2Arr 速度会提升15ms
// 这个是规定一定的方向
const num1Arr = (num1.length > num2.length ? num2 : num1).split('').map(item => item.charCodeAt(0) - left);
const num2Arr = (num1.length > num2.length ? num1 : num2).split('').map(item => item.charCodeAt(0) - left);
let res = [];
console.log("num1Arr:"+num1Arr);
console.log("num2Arr:"+num2Arr);
for (let i = num1Arr.length - 1; i > -1; i--) {
for (let j = num2Arr.length - 1; j > -1; j--) {
// 数字的相乘的结果转换为数组,并且 reverse,方便计算
const resArr = (num1Arr[i] + num2Arr[j]).toString().split('');
console.log("resArrr:"+resArr+" typeof resArr:"+typeof(resArr));
resArr.reverse();
const index = num2Arr.length - 1 - j + num1Arr.length - 1 - i;
let next = 0, k = 0;
console.log("----------");
console.log("index:"+index);
console.log("resArr of length:" +resArr.length);
while (k < resArr.length || next !== 0) {
// 结果当前位数加上前一位的进位
console.log("k: "+k)
let sum = (res[index + k] | 0) + next;//清零,再获取。
console.log("test"+resArr[index+k] | 0)
console.log("sum1: "+sum);
// 若 k < resArr,即非最后一位进位
if (k < resArr.length) {
sum += +resArr[k];
console.log("sum2: "+sum);
}
res[index + k] = sum % 10;
// 若 sum 大于10,进位 = 1
next = sum / 10 >= 1 ? 1: 0;
console.log("test :"+resArr[index+k])
console.log("next: "+next);
k++;
}
console.log("***res"+res)
console.log("resArrr1:"+resArr+" typeof resArr1:"+typeof(resArr));
}
}
console.log("-------res:"+res)
// 去除结果前的 0
while (res.length > 1 && res[res.length - 1] === 0) {
res.pop();
}
return res.reverse().join('');
};
console.log(multiply("999","3333"));
实现结果: