43. Multiply Strings
题目描述:
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.
解题思路:
从num1 和 num2的长度可以看出,直接将字符串转化成数字有溢出的可能,而且note4中也提到了不允许直接转。
我们可以将乘法分步来看:
例如 123 * 456:
实际上是用了错位相减法。
两个数相乘,其长度最多是原来长度的两倍,所以我们可以够早一个存储数组来存储当前位的数。
注意的是当前位下标的计算:
int idx = total_size - (len1 - i- 1) - (len2 - j -1);
减的是i和j与最初值的变化量。
更新存储数组的的值:
store[idx] += temp;
store[idx - 1] += (store[idx]/10);
store[idx] %= 10;
要对最终的值算进位并加到前一位
在求余就是当前值。
要记得判断首位是不是0!
代码:
class Solution { public: string multiply(string num1, string num2) { int len1 = num1.size(); int len2 = num2.size(); if(num2 == "0" || num1 == "0") return "0"; string ret; vector<int> store(len1+len2, 0); int total_size = len1 + len2 -1; for(int i = len1 - 1; i > -1; i--){ for(int j = len2 - 1; j > -1; j--){ int n1 = num1[i]-'0'; int n2 = num2[j]-'0'; int temp = n1 * n2; int idx = total_size - (len1 - i- 1) - (len2 - j -1); store[idx] += temp; store[idx - 1] += (store[idx]/10); store[idx] %= 10; } } int i = 0; while(store[i] == 0) i++; for(; i <= total_size; i++){ char c = store[i]+'0'; ret.push_back(c); } return ret; } };