Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
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 digits0-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.
题意很简单,给两个string做乘法。无需考虑一些比如string中夹杂字母的case,但是不允许将input convert成数字再做乘法。影子题415。需要注意的几个地方是
- 如果num1有i个数字,num2有j个数字,最后的结果res最多只有i + j个数字
- 细心观察之后就发现,num1[i] 和 num2[j] 的乘积只可能是一个两位数,对应的就是 res[i+j] 和 res[i+j+1] 这两个位置
https://leetcode-cn.com/problems/multiply-strings/solution/gao-pin-mian-shi-xi-lie-zi-fu-chuan-cheng-fa-by-la/
JavaScript实现
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 };
Java实现
1 class Solution { 2 public String multiply(String num1, String num2) { 3 int m = num1.length(); 4 int n = num2.length(); 5 int[] res = new int[m + n]; 6 for (int i = m - 1; i >= 0; i--) { 7 for (int j = n - 1; j >= 0; j--) { 8 int product = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); 9 int p1 = i + j; 10 int p2 = i + j + 1; 11 int sum = product + res[p2]; 12 res[p1] += sum / 10; 13 res[p2] = sum % 10; 14 } 15 } 16 StringBuilder sb = new StringBuilder(); 17 for (int p : res) { 18 if (!(sb.length() == 0 && p == 0)) { 19 sb.append(p); 20 } 21 } 22 return sb.length() == 0 ? "0" : sb.toString(); 23 } 24 }