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.
- Converting the input string to integer is NOT allowed.
- You should NOT use internal library such as BigInteger.
解答:
This is the standard manual multiplication algorithm. We use two nested for loops, working backward from the end of each input number. We pre-allocate our result and accumulate our partial result in there. One special case to note is when our carry requires us to write to our sum string outside of our for loop.
At the end, we trim any leading zeros, or return 0 if we computed nothing but zeros.
用num1.size()+num2.size()的长度作为结果,这里多了一位是怕高位有进制同时注意从不是0的数字开始,若全是0则返回字符串0
class Solution {
public:
string multiply(string num1, string num2) {
string sum(num1.size()+num2.size(),'0');
for(int i = num1.size()-1; i >= 0; i--){
int carry = 0;
for(int j = num2.size()-1; j >= 0; j--){
int temp = (sum[i + j + 1] - '0') + (num1[i] - '0')*(num2[j] - '0') + carry;
sum[i + j + 1] = temp % 10 + '0';
carry = temp / 10;
}
sum[i] += carry;
}
size_t t = sum.find_first_not_of("0");
if(t != string::npos)
return sum.substr(t);
else
return "0";
}
};