Description
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 and num2 is < 110.
- Both num1 and num2 contain only digits 0-9.
- Both num1 and num2 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.
分析
题目的意思是:求两个数字字符串的乘积。
- 把错位相加后的结果保存到一个一维数组中,然后分别在每位上算进位,最后每个数字都变成一位,然后要做的是去除掉首位0,最后把每位上的数字按顺序保存到结果中即可
C++ 代码
class Solution {
public:
string multiply(string num1, string num2) {
string res="";
int m=num1.size();
int n=num2.size();
vector<int> v(m+n,0);
int k=m+n-2;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
v[k-i-j]+=(num1[i]-'0')*(num2[j]-'0');
}
}
int carry=0;
for(int i=0;i<m+n;i++){
v[i]+=carry;
carry=v[i]/10;
v[i]=v[i]%10;
}
int i=m+n-1;
while(v[i]==0){
i--;
}
if(i<0){
return "0";
}
while(i>=0) res.push_back(v[i--]+'0');
return res;
}
};
Python 代码
class Solution:
def multiply(self, num1: str, num2: str) -> str:
res=0
m=len(num1)
n=len(num2)
res=[0]*(m+n)
k=m+n-2
for i in range(m):
for j in range(n):
res[k-i-j]+=int(num1[i])*int(num2[j])
carry=0
for i in range(m+n):
res[i]+=carry
carry=res[i]//10
res[i]=res[i]%10
i=m+n-1
while i>=0 and res[i]==0:
i-=1
res=[str(item) for item in res]
if i<0:
return '0'
return ''.join(reversed(res[:i+1]))