您的位置:首页 > 其它

leetcode: Multiply Strings

2013-11-07 15:27 435 查看
http://oj.leetcode.com/problems/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.


思路

这是一道经常出现的面试题。竖式乘法怎么做的照搬就可以,注意看代码,用一个string搞定。

class Solution {
public:
string multiply(string num1, string num2) {
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());

if (("0" == num1) || ("0" == num2)) {
return "0";
}

string result = "";
int i, j;
int flag = 0, steps = 0;

for (int i = 0; i < num1.length(); ++i) {
int position = steps;

for (int j = 0; j < num2.length(); ++j) {
int v = (num1[i] - '0') * (num2[j] - '0') + flag;

if (position < result.length()) {
v += result[position] - '0';
result[position] = (v % 10) + '0';
}
else {
result.append(1, (v % 10) + '0');
}

flag = v / 10;
++position;
}

if (flag > 0) {
result.append(1, flag + '0');
}

flag = 0;
++steps;
}

reverse(result.begin(), result.end());

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: