您的位置:首页 > 其它

Multiply Strings leetcode

2016-01-11 21:17 459 查看
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.

Subscribe to see which companies asked this question

ACM竞赛常考的大数相乘算法,利用字符串来表示大数字进行计算。

string multiply(string num1, string num2) {
string num(num1.size() + num2.size(), '0');
for (int i = num1.size() - 1; i >= 0; --i)
{
int carry = 0;
for (int j = num2.size() - 1; j >= 0; --j)
{
int tmp = num[i + j + 1] - '0' + (num1[i] - '0') * (num2[j] - '0') + carry;
num[i + j + 1] = tmp % 10 + '0';
carry = tmp / 10;
}
num[i] += carry;
}
size_t startpos = num.find_first_not_of('0');
if (startpos != string::npos)
return num.substr(startpos);
return "0";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: