## LeetCode题解：Multiply Strings

2018年03月31日 ⁄ 综合 ⁄ 共 1373字 ⁄ 字号 评论关闭

### Multiply Strings

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:
void accumulate_string(string& s1, const string& s2)
{
string sum;
sum.resize(max(s1.size(), s2.size()));
int riter = sum.size() - 1;

int s1_adjust = sum.size() - s1.size();
int s2_adjust = sum.size() - s2.size();

char incr = 0;

while(riter >= 0)
{
int s1iter = riter - s1_adjust;
char v1 = (s1iter >= 0 ? s1[s1iter] : '0');
int s2iter = riter - s2_adjust;
char v2 = (s2iter >= 0 ? s2[s2iter] : '0');

char s = v1 + v2 - 2 * '0' + incr;

if (s >= 10)
incr = 1, s -= 10;
else
incr = 0;

sum[riter] = s + '0';
--riter;
}

s1 = (incr == 0 ? string("") : string("1")) + sum;
}

void multiple_strch(string& s1, char ch)
{
string product;
product.resize(s1.size());

if (ch == '0')  // avoid "0000" problem
{
s1 = "0";
return;
}

if (ch == '1') // accelerate
return;

char chval = ch - '0';
char incr = 0;
auto piter = product.rbegin();
for(auto iter = s1.rbegin(); iter != s1.rend(); ++iter, ++piter)
{
char val = (*iter - '0') * chval + incr;
incr = val / 10;
val -= incr * 10;
val += '0';
*piter = val;
}
s1 = (incr == 0 ? string("") : string(1, incr + '0')) + product;
}

string multiply(string& s1, string& s2)
{
if (s1.size() < s2.size())
swap(s1, s2);

string sum="0";
int i = 0;
for(auto iter = s2.rbegin(); iter != s2.rend(); ++iter, ++i)
{
string prod = s1 + string(i, '0');
multiple_strch(prod, *iter);
accumulate_string(sum, prod);
}
return sum;
}
};```