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.
思路:利用传统的方法,将乘法分解为加法,代码如下:
class Solution {
public:
string genZero(int n){//生成n个0组成的字符串
string s = "";
for(int i = 0; i < n; ++i)
s += '0';
return s;
}
string stringPlus(string num1, string num2){//字符串加法
string s = "";
int len1 = num1.length();
int len2 = num2.length();
if(len1 == 0)
return num2;
if(len2 == 0)
return num1;
int i = len1 - 1, j = len2 - 1;
int jinwei = 0;
while(i >= 0 && j >= 0){
int a = num1[i--] - '0';
int b = num2[j--] - '0';
int c = a + b + jinwei;
s += c % 10 + '0';
jinwei = c / 10;
}
while(i >= 0){
int a = num1[i--] - '0';
int c = a + jinwei;
s += c % 10 + '0';
jinwei = c / 10;
}
while(j >= 0){
int b = num2[j--] - '0';
int c = b + jinwei;
s += c % 10 + '0';
jinwei = c / 10;
}
if(jinwei){
s += '1';
}
string sum = "";
for(i = s.length() - 1; i >= 0; i--)
sum += s[i];
return sum;
}
string multiplyChar(string num, char c){//字符串乘以某一字符,例如“123” × ‘2’ = “246”
int n = c - '0';//n=[0-9]
if(n == 0)
return "0";
if(n == 1)
return num;
string ret = num;
for(int i = 1; i < n; ++i){
ret = stringPlus(num, ret);
}
return ret;
}
string multiply(string num1, string num2){//字符串乘法
int len1 = num1.length();
int len2 = num2.length();
if(len1 == 0 || len2 == 0)
return "";
if(len1 > len2){
swap(num1, num2);
swap(len1, len2);
}
string ret = "";
for(int i = len1 - 1; i >= 0; --i){
string tmp = multiplyChar(num2, num1[i]) + genZero(len1 - 1 - i);
ret = stringPlus(ret, tmp);
}
return ret;
}
};