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.
题目解析:
方案一:
模拟数据的乘法
class Solution {
public:
string multiply(string num1, string num2) {
string s(num1.size() + num2.size(), '0');
//将数据翻转,方便求解
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
//num1的每一位与num2相乘
for(int i = 0; i < num1.size(); i++)
{
int flag = 0;
for(int j = 0; j < num2.size(); j++)
{
int digit = s[i+j] - '0';
int num = (num1[i] - '0') * (num2[j] - '0');
int res = digit + num + flag;
s[i+j] = (res % 10) + '0';
flag = res / 10;
}
int index = i + num2.size();
while(flag) //如果有进位,则修改高位的值
{
int digit = s[index] - '0';
int res = digit + flag;
s[index] = (res % 10) + '0';
flag = res / 10;
}
}
//去除高位为0的多余字符
while(true)
{
if (s[s.size()-1] == '0' && s.size() > 1)
s.erase(s.size() - 1, 1);
else
break;
}
//翻转
reverse(s.begin(), s.end());
return s;
}
};
方案二:
先乘,然后再处理进位。由于我们的数据是反着的,所有程序中相乘的表达式有res[i+j+1] += n1[i]*n2[j];
按照正常的话:比如45 * 35
流程是:先让35的每一位与45的位分别相乘,得到结果不进位,最后再处理进位的问题。
当然35和45的位从右向左标记的话,就是res[i+j] += n1[i] * n2[j];
class Solution {
public:
string multiply(string num1, string num2) {
if(num1=="0" || num2=="0")
return "0";
int l1 = num1.length(), l2 = num2.length();
int* n1 = new int[l1];
int* n2 = new int[l2];
int* res = new int[l1+l2];
memset(res,0,sizeof(int)*(l1+l2));
for(int i=0; i<l1; ++i)
n1[i] = num1[i] - '0';
for(int i=0; i<l2; ++i)
n2[i] = num2[i] - '0';
//好好看例子
for(int i=0; i<l1; ++i)
for (int j=0; j<l2; ++j)
res[i+j+1] += n1[i]*n2[j];
string ss = "";
for (int k=l1+l2-1; k>=0; --k){
if(k>0)
res[k-1] += res[k]/10;
res[k] %= 10;
ss = char(res[k]+'0')+ss;
}
ss = ss[0]=='0'? ss.substr(1):ss;
return ss;
}
};