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.
思路:直观思路,就是模拟乘法过程。注意进位。我写的比较繁琐。
string multiply(string num1, string num2) {
vector<int> v1, v2, vmulti;
vector<vector<int>> vvtmp;
int l1 = num1.size();
int l2 = num2.size(); if(l1 == && num1[] == '') return "";
if(l2 == && num2[] == '') return ""; int maxl = ;
//用vector存储两个数字 v[0]是最高位
for(int i = ; i < l1; i++)
v1.push_back(num1[i] - '');
for(int i = ; i < l2; i++)
v2.push_back(num2[i] - ''); //乘步骤
for(int i = l1 - ; i >= ; i--)
{
vector<int> vtmp; //v[0]是最低位
int t = i;
while(t < l1 - ) //后面补错位的0
{
vtmp.push_back();
t++;
}
int c = ; //记录进位
for(int j = l2 - ; j >= ; j--)
{
int cur = v1[i] * v2[j] + c;
vtmp.push_back(cur % );
c = cur / ;
}
if(c != )
vtmp.push_back(c);
vvtmp.push_back(vtmp);
maxl = (vtmp.size() > maxl) ? vtmp.size() : maxl;
} //加步骤
int c = ; //记录进位
for(int i = ; i < maxl; i++)
{
int cur = c;
for(int j = ; j < vvtmp.size(); j++)
{
if(i >= vvtmp[j].size())
continue;
cur += vvtmp[j][i];
}
vmulti.push_back(cur % );
c = cur / ;
}
if(c != )
vmulti.push_back(c); //转换为string
string ans;
for(int i = vmulti.size() - ; i >= ; i--)
{
ans += (vmulti[i] + '');
} return ans;
}
大神总是能把多个步骤一次到位:
string multiply(string num1, string num2) {
string sum(num1.size() + num2.size(), ''); for (int i = num1.size() - ; <= i; --i) {
int carry = ;
for (int j = num2.size() - ; <= j; --j) {
int tmp = (sum[i + j + ] - '') + (num1[i] - '') * (num2[j] - '') + carry; //把当前乘出来的数字和之前的数字以及进位相加
sum[i + j + ] = tmp % + '';
carry = tmp / ;
}
sum[i] += carry; //这个是最高位多出来的进位 其他的都是i+j+1 这里没有+1
} size_t startpos = sum.find_first_not_of("");
if (string::npos != startpos) {
return sum.substr(startpos);
}
return "";
}