Open guodongxiaren opened 4 years ago
// Example program
#include <iostream>
#include <string>
#include <algorithm>
#include <sstream>
using namespace std;
string add(const string& A, const string& B) {
string a(A);
string b(B);
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int ia = 0, ib = 0;
int la = a.size(), lb = b.size();
int t = 0;
stringstream ss;
while (ia < la || ib < lb) {
if (ia < la) {
t += a[ia++] - '0';
}
if (ib < lb) {
t += b[ib++] - '0';
}
ss<<t%10;
t /= 10;
}
// t == 1
if (t > 0) {
ss<<t;
}
string s = ss.str();
reverse(s.begin(), s.end());
return s;
}
int main() {
cout<<add("123", "456")<<endl;
cout<<add("123", "4567")<<endl;
cout<<add("4567", "123")<<endl;
}
考虑最简单的情况,只有正整数的情况。