我之前提交的代码
vector<int> myadd(vector<int>& va, vector<int>&vb) {
if (va.size() == 0) return vb;
if (vb.size() == 0) return va;
int carry = 0;
int i = 0, j = 0;
vector<int> vc;
while(i < va.size() && j < vb.size()) {
int res = va[i] + vb[j] +carry;
if (res > 9) {
res -= 10;
carry = 1;
} else {
carry = 0;
}
vc.push_back(res);
i ++;
j ++;
}
while(i < va.size()) {
int res = va[i] + carry;
if (res > 9) {
res -= 10;
carry = 1;
} else {
carry = 0;
}
vc.push_back(res);
i ++;
}
while(j < vb.size()) {
int res = vb[j] + carry;
if (res > 9) {
res -= 10;
carry = 1;
} else {
carry = 0;
}
vc.push_back(res);
j ++;
}
if (carry) {
vc.push_back(carry);
}
return vc;
}
简单好懂,易于调试,适合初学者。
模板代码
vector<int> add(vector<int>& va, vector<int>& vb) {
if (va.size() == 0) return vb;
if (vb.size() == 0) return va;
if (va.size() < vb.size()) {
return add(vb, va);
}
vector<int> vc;
int t = 0;
for (int i = 0; i < va.size(); i ++) {
t += va[i];
if (i < vb.size()) t += vb[i];
vc.push_back(t % 10);
t /= 10;
}
if (t) vc.push_back(t);
return vc;
}
简洁高效,适合背诵。