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 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.
解析
实现字符串的乘法。自己写的时候是每一个字符去乘另一个字符得到字符串再相加,看了大神的解法后,觉得自己的太naive了。

两个数相乘得到的数的长度为两个数长度之和,并且两个数的位置相乘得到的数在i+j和i+j+1两个位置上。从后往前乘。
自己写的垃圾
class Solution {
public:
string add(string num1, string num2){
int len1 = num1.size();
int len2 = num2.size();
int i=0,j=0;
int carry = 0;
string res = "";
while(i<len1 && j<len2){
res += (((num1[i] -'0')+(num2[j]-'0')+carry)%10) + '0';
carry = ((num1[i] -'0')+(num2[j]-'0')+ carry) / 10;
i++;j++;
}
while(i<len1){
res += (((num1[i] -'0')+carry)%10) + '0';
carry = ((num1[i] -'0')+carry)/10;
i++;
}
while(j<len2){
res += (((num2[j] -'0')+carry)%10) + '0';
carry = ((num2[j] -'0')+carry)/10;
j++;
}
if(carry>0)
res += (carry+'0');
return res;
}
string multiply(string num1, string num2) {
if(num1 == "0" || num2 == "0")
return "0";
int len1 = num1.size();
int len2 = num2.size();
if(len2 > len1){
string tmp = num2;
num2 = num1;
num1 = tmp;
}
len1 = num1.size(); len2 = num2.size();
string res = "";
string carry = "";
for(int i=len2-1;i>=0;i--){
int carry1 = 0;
string tmp = "";
for(int j=len1-1;j>=0;j--){
char ch = (((num2[i] -'0')*(num1[j]-'0') + carry1)%10) + '0';
cout<<ch<<endl;
tmp += (((num2[i] -'0')*(num1[j]-'0') + carry1)%10) + '0';
carry1 = ((num2[i] -'0')*(num1[j]-'0')+ carry1)/10;
}
if(carry1>0)
tmp += (carry1+'0');
tmp = carry + tmp;
carry += '0';
res = add(res, tmp);
}
reverse(res.begin(),res.end());
return res;
}
};
大神解法
class Solution {
public:
string multiply(string num1, string num2) {
if(num1 == "0" || num2 == "0")
return "0";
int len1 = num1.size();
int len2 = num2.size();
string result = "";
vector<int> res(len1+len2, 0);
for(int i=len2-1;i>=0;i--){
for(int j=len1-1;j>=0;j--){
int mul = (num2[i]-'0')*(num1[j]-'0');
res[i+j] += (mul+res[i+j+1])/10;
res[i+j+1] = (mul+res[i+j+1])%10;
}
}
for(int i=0;i<len1+len2;i++){
if (!result.empty() || res[i] != 0)
result += (res[i] + '0');
}
return result;
}
};
本文介绍了一种不使用内置大整数库实现两个非负整数相乘的方法,通过字符串形式输入并返回乘积的字符串表示。文章对比了两种实现方式:一种是逐位相乘再累加;另一种是更高效的利用数组进行位运算。
981

被折叠的 条评论
为什么被折叠?



