LeetCode 43. 字符串相乘(string * string)
原题链接
中等
作者:
Value
,
2020-08-13 13:34:05
,
所有人可见
,
阅读 399
class Solution {
public:
string mul(string a, int p){
int cnt = 0;
reverse(a.begin(), a.end());
string s = "";
for(int i = 0; i < a.size(); i ++ ){
int num = p * (a[i] - '0') + cnt;
if(num < 10){
cnt = 0;
s += (num + '0');
}
else{
cnt = num / 10;
s += (num % 10 + '0');
}
}
if(cnt) s += (cnt + '0');
// 去除可能的前缀0
int i = s.size() - 1;
while(i >= 0){
if(s[i] != '0') break;
i -- ;
}
if(i == -1) return "0";
string res = "";
while(i >= 0){
res += s[i -- ];
}
return res;
}
string add(string a, string b){
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int cnt = 0, i;
string s = "";
for(i = 0; i < a.size() && i < b.size(); i ++ ){
int num = a[i] + b[i] - 2 * '0' + cnt;
if(num < 10){
cnt = 0;
s += (num + '0');
}
else{
cnt = 1;
s += (num - 10 + '0');
}
}
while(i < a.size()){
int num = a[i] - '0' + cnt;
if(num < 10){
cnt = 0;
s += (num + '0');
}
else{
cnt = 1;
s += (num - 10 + '0');
}
i ++ ;
}
while(i < b.size()){
int num = b[i] - '0' + cnt;
if(num < 10){
cnt = 0;
s += (num + '0');
}
else{
cnt = 1;
s += (num - 10 + '0');
}
i ++ ;
}
if(cnt) s += (cnt + '0');
reverse(s.begin(), s.end());
return s;
}
string multiply(string num1, string num2) {
if(num1 == "0" || num2 == "0") return "0";
string res = "0";
reverse(num2.begin(), num2.end());
for(int i = 0; i < num2.size(); i ++ ){
int p = num2[i] - '0';
string tmp = mul(num1, p);
for(int mov = 1; mov <= i; mov ++ ) tmp += '0';
res = add(res, tmp);
}
return res;
}
};