题意很简单,给两个string做乘法。无需考虑一些比如string中夹杂字母的case。这里有一个discussion把思路已经解释的非常明白了,我就不讲思路了,直接上代码。
1 /** 2 * @param {string} num1 3 * @param {string} num2 4 * @return {string} 5 */ 6 var multiply = function(num1, num2) { 7 let m = num1.length; 8 let n = num2.length; 9 let pos = new Array(m + n).fill(0); 10 11 for (let i = m - 1; i >= 0; i--) { 12 for (let j = n - 1; j >= 0; j--) { 13 let mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); 14 let p1 = i + j; 15 let p2 = i + j + 1; 16 let sum = mul + pos[p2]; 17 pos[p1] += Math.floor(sum / 10); 18 pos[p2] = sum % 10; 19 } 20 } 21 let res = ''; 22 for (let p of pos) { 23 if (!(res.length === 0 && p === 0)) { 24 res += p; 25 } 26 } 27 return res.length === 0 ? '0' : res; 28 };