0043. Multiply Strings (M)
Multiply Strings (M)
题目
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.
题意
不使用内建库实现大数乘法。
思路
- m位数乘n位数得到的积最大位数为m+n,直接开一个m+n大的数组来存储积的每一位数;
- num1中i位置的数与num2中j位置的数相乘,所得积在新数组中的位置为i+j+1(位置i+j是留给进位的),每次计算积后累加在对应位置,可以先不考虑进位,之后再处理;
- 从右向左遍历新数组,处理进位;
- 将新数组转化为字符串。(注意第一个元素为0的情况)
代码实现
Java
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
int[] array = new int[num1.length() + num2.length()];
for (int i = 0; i < num1.length(); i++) {
for (int j = 0; j < num2.length(); j++) {
int x = num1.charAt(i) - '0';
int y = num2.charAt(j) - '0';
array[i + j + 1] += x * y;
}
}
int carry = 0;
for (int i = array.length - 1; i >= 0; i--) {
int sum = array[i] + carry;
array[i] = sum % 10;
carry = sum / 10;
}
StringBuilder sb = new StringBuilder();
// 第一个为0则不加入字符串中
for (int i = array[0] == 0 ? 1 : 0; i < array.length; i++) {
sb.append((char) (array[i] + '0'));
}
return sb.toString();
}
}
JavaScript
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var multiply = function (num1, num2) {
if (num1 === '0' || num2 === '0') {
return '0'
}
let product = new Array(num1.length + num2.length).fill(0)
for (let i = 0; i < num1.length; i++) {
for (let j = 0; j < num2.length; j++) {
product[i + j + 1] += num1[i] * num2[j]
}
}
for (let i = product.length - 1; i >= 0; i--) {
if (i > 0 && product[i] >= 10) {
product[i - 1] += Math.trunc(product[i] / 10)
product[i] %= 10
}
}
if (product[0] === 0) {
product = product.slice(1)
}
return product.join('')
}
参考