您的位置:首页 > 其它

Leetcode Multiply Strings

2015-11-23 14:09 330 查看
Leetcode Multiply Strings 相关代码,本处同时可以做为相加时的算法,相关代码如下:

#include<iostream>
#include<string>

/*
* We use the recursive algorithm to solve this proble. We can conclued that
* the number with more digits can be construct by the less.
*/
using namespace std;
class Solution {
public:
string multiply(string num1, string num2) {
int len1 = num1.length();
int len2 = num2.length();
if (len1 == 0 || len2 == 0 || num1 == "0" || num2 == "0") {
return "0";
}
len1 --;
len2 --;
string pre = "";
string curent = "";
string re = "";
int tmp;
int carry = 0;
int value = 0;
char digit;
for (int i = len2; i >= 0; i --) {
curent = pre;
pre = pre + "0";
value = num2[i] - '0';
carry = 0;
for (int j = len1; j >= 0; j --) {
tmp = value * (num1[j] - '0') + carry;
digit = tmp % 10 + '0';
carry = tmp / 10;
curent = digit + curent;
}
if (carry != 0) {
curent = to_string(carry) + curent;
}
re = add(re, curent);
}
return re;
}

string add(string num1, string num2) {
int len1 = num1.length();
int len2 = num2.length();
if (len1 == 0) {
return num2;
}
if (len2 == 0) {
return num1;
}
int carry = 0;
string re = "";
char digit;
int tmp;
len1 = len1 - 1;
len2 = len2 - 1;
while (len1 >= 0 && len2 >= 0) {
tmp = (num1[len1] - '0') + (num2[len2] - '0') + carry;
digit = tmp % 10 + '0';
re = digit + re;
carry = tmp / 10;
len1 --;
len2 --;
}
while (len1 >= 0) {
tmp = (num1[len1] - '0') + carry;
digit = tmp % 10 + '0';
re = digit + re;
carry = tmp / 10;
len1 --;
}
while (len2 >= 0) {
tmp = (num2[len2] - '0') + carry;
digit = tmp % 10 + '0';
re = digit + re;
carry = tmp / 10;
len2 --;
}
if (carry) {
re = to_string(carry) + re;
}
return re;
}
};

// Sample input: ./a.out argv1
int main(int argc, char* argv[]) {
Solution so;
string re = so.multiply(argv[1], argv[2]);
cout<<"result: "<<re<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leetcode