leetcode[43]Multiply Strings
4754 ワード
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
Note: The numbers can be arbitrarily large and are non-negative.
class Solution {
public:
string multiply(string num1, string num2)
{
if(num1=="0"||num2=="0")return "0";
int len1=num1.size();
int len2=num2.size();
int *n1=new int[len1];
int *n2=new int[len2];
for (int i=0;i<len1;i++)
{
n1[i]=num1[i]-'0';
}
for (int i=0;i<len2;i++)
{
n2[i]=num2[i]-'0';
}
int *res=new int[len1+len2];
memset(res,0,(len1+len2)*sizeof(int));
for (int i=len1-1;i>=0;i--)
{
for (int j=len2-1;j>=0;j--)
{
res[i+j+1]+=n1[i]*n2[j];
}
}
string result="";
for (int k=len1+len2-1;k>=0;k--)
{
if(k>0) res[k-1]+=res[k]/10;
res[k]%=10;
result=char(res[k]+'0')+result;
}
if(result[0]=='0')return result.substr(1,result.size());
return result;
}
};