leetcode 43. 字符串相乘(Multiply Strings)
目录
题目描述:
给定两个以字符串形式表示的非负整数 num1
和 num2
,返回 num1
和 num2
的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:
输入: num1 = "123", num2 = "456"
输出: "56088"
说明:
num1
和num2
的长度小于110。num1
和num2
只包含数字0-9
。num1
和num2
均不以零开头,除非是数字 0 本身。- 不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
解法:
class Solution {
public:
string multi(string& s, char ch){
if(ch == '0'){
return "0";
}else if(ch == '1'){
return s;
}
string res = "";
int sz = s.size();
int carry = 0;
for(int i = sz-1; i >= 0; i--){
int val = carry + int(s[i] - '0')*int(ch - '0');
carry = val / 10;
val %= 10;
res = char(val + '0') + res;
}
if(carry != 0){
res = char(carry + '0') + res;
}
return res;
}
string add(const string& s, const string& t){
string res = "";
int sz1 = s.size();
int sz2 = t.size();
int i = sz1-1, j = sz2-1;
int carry = 0;
while(i >= 0 || j >= 0 || carry > 0){
int d1 = (i >= 0) ? int(s[i] - '0') : 0;
int d2 = (j >= 0) ? int(t[j] - '0') : 0;
int d = d1 + d2 + carry;
carry = d/10;
d %= 10;
res = char(d + '0') + res;
i--;
j--;
}
return res;
}
string multiply(string num1, string num2) {
if(num1 == "0" || num2 == "0"){
return "0";
}else{
int sz1 = num1.size();
int sz2 = num2.size();
string s = num1, t = num2;
if(sz1 <= sz2){
t = num1;
s = num2;
}
string res = "";
for(char ch : t){
res += '0';
res = add(res, multi(s, ch));
}
return res;
}
}
};

更多精彩