您的位置:首页 > 其它

[LeetCode]Multiply Strings

2016-04-20 11:21 405 查看
一、问题描述:

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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.

二、问题分析:
题目就是模拟乘法操作,而且还是非负数,这样就比较简单了。
原本用了分治的方法去做,而且明显时间复杂度比模拟低,但竟然超时了......为了避免以后重复造轮子,这次把模拟乘法的代码贴出来。其中注释部分去掉之后为正负通用的乘法。
还有一个比较蛋疼的是命令行下to_string()总是找不到,干脆自己写一个好了(虽然这道题只是在调试的时候用了下...)
public:
string multiply(string num1, string num2) {
string ans(num1.length()+num2.length(), '0');
int PN = 1, n = ans.length();
if (num1.length()<1 || num2.length()<1) return ans;
if (num1 == "0" || num2 == "0") return "0";
// if (num1 == "-") {
// 	PN *= (-1);
// 	num1 = num1.substr(1, num1.length()-1);
// }
// if (num2 == "-") {
// 	PN *= (-1);
// 	num2 = num2.substr(1, num2.length()-1);
// }
for (int i = num1.length()-1; i >= 0; --i, --n) {
int carry = 0, pos = n-1;
for (int j = num2.length()-1; j >= 0; --j, --pos) {
int charMult = (num1[i]-'0')*(num2[j]-'0')+carry+ans[pos]-'0';
carry = charMult/10;
ans[pos] = charMult%10+'0';
}
while (carry) {
int charAdd = (ans[pos]-'0')+carry;
carry = charAdd/10;
ans[pos--] = charAdd%10+'0';
}
}
int i = 0;
for(; i<ans.length() && ans[i]=='0'; i++);
ans = ans.substr(i, ans.length()-i);
// if (PN == -1) ans = "-"+ans;
return ans;
}
private:
string to_string(int i) {
stringstream ss;
ss << i;
string s;
ss >> s;
return s;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: