题目如下:
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.
分析如下:
以 1234 * 567 = 69978为例。假设
num1 = 1234
num2 = 567
那么可以模拟乘法,用num2 的每一位去乘以num1,得到一个结果, num2 的低位开始,到高位结束,乘积依次是
1234 * 7 = 8638 ----> 8638
1234 * 6 = 7404 ----> 74040
1234 * 5 = 6170 ----> 617000
然后, 每次得到的结果要根据情况乘以扩大10的N倍,最后把这个结果加起来。
我的代码:
//209ms
/*
1234
X 567
------------
8638
7404
6170
------------
699678
*/
class Solution {
public:
string add_string(string & s1, string & s2) {
if (s1 == "" ) return s2;
int len1 = s1.length();
int len2 = s2.length();
int i = len1 - 1;
int j = len2 - 1;
int rounding = 0;
string res = "";
while (i >=0 && j >= 0) {
res = to_string((rounding + s1[i] - '0' + s2[j] - '0') % 10) + res;
rounding = (rounding + s1[i] - '0' + s2[j] - '0') / 10;
--i;
--j;
}
while (i >= 0) {
res = to_string((rounding + s1[i] - '0' ) % 10) + res;
rounding = (rounding + s1[i] - '0' ) / 10;
--i;
}
while (j >= 0) {
res = to_string((rounding + s2[j] - '0') % 10) + res;
rounding = (rounding + s2[j] - '0') / 10;
--j;
}
if (rounding > 0)
res = to_string(rounding) + res;
return res;
}
string multiply(string num1, string num2) {
if (num1.size() == 0 || num1 == "0" ) return "0";
if (num2.size() == 0 || num2 == "0" ) return "0";
string each_res = "";
string final_res = "";
string add_zero = "";
int rounding = 0;
for (int i = num2.size() - 1; i >= 0; --i) {
each_res = "";
rounding = 0;
for (int j = num1.size() - 1; j >= 0; --j) {
each_res = to_string((rounding + (num2[i] - '0') * (num1[j] - '0')) % 10) + each_res;
rounding = (rounding + (num2[i] - '0') * (num1[j] - '0')) / 10;
}
if (rounding > 0)
each_res = to_string(rounding) + each_res;
each_res = each_res + add_zero;
add_zero = add_zero + "0";
final_res = add_string(final_res, each_res);
//std::cout<<"each_res = "<<each_res<<", final_res = "<<final_res<<std::endl;
}
return final_res;
}
};