LeetCode 43. Multiply Strings
Solution1:我的答案
作为一个hard题,提交一次就过真是让我hin开心啊!!!
就是方法有点笨。。
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") return "0";
string res = "";
vector<string> temp_res;
int max_size = 0, i = 0, carry = 0;
for (int i = num2.size() - 1; i >= 0; i--) {
string temp_str = my_multi(num1, num2[i]);
string space(num2.size() - 1 - i, ' ');
temp_str = temp_str + space;
max_size = max(max_size, (int)temp_str.size());
temp_res.push_back(temp_str);
}
while (i < max_size) { //i的最大索引值为max_size-1
int temp_sum = 0;
for (int j = 0; j < temp_res.size(); j++) { //遍历所有的加数
if (i <= temp_res[j].size() - 1) {
int index = temp_res[j].size() - 1 - i;
if (temp_res[j][index] == ' ')
continue;
else
temp_sum += temp_res[j][index] - '0';
}
}
res = to_string((carry + temp_sum) % 10) + res;
carry = (carry + temp_sum) / 10;
i++;
}
if (carry)
res = to_string(carry) + res;
return res;
}
// 子函数为多位数和1位数相乘
string my_multi(string &num1, char num2) {
string res = num1;
int i = num1.size() - 1, temp1 = 0, temp_sum = 0, carry = 0;
for (; i >= 0; i--) {
temp_sum = (num1[i] - '0') * (num2 - '0');
res[i] = (carry + temp_sum) % 10 + '0';
carry = (carry + temp_sum) / 10;
}
if (carry)
res = to_string(carry) + res;
return res;
}
};
Solution2:花花酱
参考网址:https://zxi.mytechroad.com/blog/simulation/leetcode-43-multiply-strings/
花花酱真牛逼啊。。。
这种方法不知道好到哪里去了~~~
Time complexity:
O(l1∗l2)
O
(
l
1
∗
l
2
)
Space complexity:
O(l1+l2)
O
(
l
1
+
l
2
)
说明:两个位数分别是m,n的整数相乘,则乘积最多有m+n位。
这么理解:比如m=3,n=2时最大乘积是999*99,考虑1000*100 = 100000,前者乘积的位数肯定小于后者,而100000有6位数,100000-1 = 99999,有5位数,所以前者乘积最多是5位数,即m+n
// Author: Huahua
// Running time: 4 ms
class Solution {
public:
string multiply(string num1, string num2) {
const int l1 = num1.length();
const int l2 = num2.length();
string ans(l1 + l2, '0');
for (int i = l1 - 1; i >= 0; --i)
for (int j = l2 - 1; j >= 0; --j) {
//这个算法中很核心的一点:就是乘数中的i,j位的乘积对应积中的第(i+j+1)位数字
int sum = (ans[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0');
ans[i + j + 1] = (sum % 10) + '0';
ans[i + j] += sum / 10;
}
for (int i = 0; i < ans.length(); ++i)
// if()中第二个条件是处理至少一个数为0的情况
if (ans[i] != '0' || i == ans.length() - 1)
return ans.substr(i);
return "";
}
};