题目:
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.
思路比较简单,不多说啦
几个需要注意的点:
1. 高位多个为0的,需要进行判断
2. 如果乘数为0的话,可以直接跳过,能节省不少时间
3. string 的两个使用
1) 创建有 len 长的 ‘0’串 string str(len, '0')
2) string 的反转 reverse(str.begin(), str.end()) 反转后操作好像更容易理解~
class Solution {
public:
string multiply(string num1, string num2) {
int size1 = num1.size();
int size2 = num2.size();
string result(size1 + size2 + , '');
reverse(num1.begin(),num1.end());
reverse(num2.begin(), num2.end());
for(int j = ; j < size2; ++j){//num2
if(num2[j] == '')
continue;
int k = j;
for(int i = ; i < size1; ++i){//num1
int tmp = (num1[i] - '') * (num2[j] - '') + result[k] - '';
result[k] = tmp % + '';
result[k + ] = result[k + ] + tmp / ;
++k;
}
}
while(!result.empty() && result.back() == '') result.pop_back();
if(result.empty()) return "";
reverse(result.begin(), result.end());
return result;
}
};