这种题目看起来简单,但是逻辑实现起来也不容易。一开始,思路没有打开,容易陷入拆东墙补西墙的修bug过程。
第一个版本啰嗦且没有可读性:
class Solution {
public:
string multiply(string num1, string num2) {
int n1 = num1.size();
int n2 = num2.size();
if(n1 == 0 || n2 == 0) return "";
if(n1 == 1 && num1[0] == '0') return "0";
if(n2 == 1 && num2[0] == '0') return "0";
string result = "";
string prevacc = "";
for(int i=n2 - 1; i >= 0; i--){
int bit2 = num2[i] - '0';
int d = 0;
string acc = "";
for(int j=n1 - 1; j >= 0; j--){
int bit1 = num1[j] - '0';
int m = bit1 * bit2 + d;
d = m / 10;
acc.push_back(m % 10 + '0');
}
if(d)
acc.push_back(d + '0');
//acc is inverse order
cout << acc <<endl;
cout << prevacc<<endl;
int ka = 0, kp = 0;
d = 0;
while(ka < acc.size() && kp < prevacc.size()){
int s = acc[ka] - '0' + prevacc[kp] - '0' + d;
acc[ka] = s % 10 + '0';
d = s / 10;
ka++;
kp++;
}
if(d){
while(ka < acc.size()){
int s = acc[ka] - '0' + d;
acc[ka] = s % 10 + '0';
d = s / 10;
ka++;
}
if(d)
acc.push_back('0' + d);
}
cout << acc<<endl;
result.push_back(acc[0]);
prevacc = acc.substr(1, acc.size());
}
result += prevacc;
if(result.back() == '0')
result.pop_back();
reverse(result.begin(), result.end());
return result;
}
};
借鉴了网上大神的版本,读完之后神清气爽。以后遇到这种题目,思路要开阔,直接开一个da'shu
class Solution {
public:
string multiply(string num1, string num2) {
int l1 = num1.size(), l2 = num2.size();
if(l1 == 0 || l2 == 0) return "0";
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
string result(l1 + l2, '0');
int num, res;
for(int i=0; i<l1; i++){
int carry = 0;
for(int j=0; j<l2; j++){
num = result[i + j] - '0';
res = (num1[i] - '0') * (num2[j] - '0') + num + carry;
carry = res / 10;
result[i + j] = res % 10 + '0';
}
int k = i + l2;
if(carry){
res = result[k] - '0' + carry;
carry = res / 10;
result[k] = res % 10 + '0';
}
}
int z = result.size() - 1;
while(result[z] == '0'){
z--;
}
if(z < 0) return "0";
result = result.substr(0, z + 1);
reverse(result.begin(), result.end());
return result;
}
};

博客提到一些题目看似简单,但逻辑实现不易,初始思路易受限,陷入修bug困境。第一个版本代码啰嗦无可读性,借鉴网上大神版本后思路开阔,提醒遇到此类题目要打开思路。
563

被折叠的 条评论
为什么被折叠?



