如下所示
include [HTML_REMOVED]
include [HTML_REMOVED]
using namespace std;
bool PAN(vector[HTML_REMOVED] X, vector[HTML_REMOVED] Y)
{
if (X.size() > Y.size())
return true;
if (X.size() < Y.size())
return false;
for (int i = X.size() - 1; i >= 0; i–)
{
if (X[i] > Y[i])
return true;
if (X[i] < Y[i])
return false;
}
return true;
}
vector[HTML_REMOVED] ADD(vector[HTML_REMOVED] x, vector[HTML_REMOVED] y)
{
int t = 0;
vector[HTML_REMOVED] OUT;
for (int i = 0; i < x.size() || i < y.size(); i++)
{
if (i < x.size())
t += x[i];
if (i < y.size())
t += y[i];
OUT.push_back(t % 10);
t /= 10;
}
if (t)
OUT.push_back(t);
return OUT;
}
vector [HTML_REMOVED] Sub(vector[HTML_REMOVED] X, vector[HTML_REMOVED] Y)
{
vector[HTML_REMOVED] Z;
int t = 0;
for (int i = 0; i < X.size(); i++)
{
t = X[i] - t;
if (i < Y.size())
t -= Y[i];
Z.push_back((t + 10) % 10);
if (t < 0)
t = 1;
else
t = 0;
}
while (Z.size() > 1 && Z.back() == 0)
Z.pop_back();
return Z;
}
static void Count(string X, string Y)
{
vector[HTML_REMOVED] A, B;
if (X[0] == '-' && Y[0] == '-')
{
X.erase(0, 1);
Y.erase(0, 1);
for (int i = X.size() - 1; i >= 0; i--)
A.push_back(X[i] - '0');
for (int i = Y.size() - 1; i >= 0; i--)
B.push_back(Y[i] - '0');
if (PAN(A, B))
{
vector<int> E = Sub(A, B);
cout << '-';
for (int i = E.size() - 1; i >= 0; i--)
cout << E[i];
}
else
{
vector<int> E = Sub(B, A);
for (int i = E.size() - 1; i >= 0; i--)
cout << E[i];
}
return;
}
if (Y[0] == '-')
{
Y.erase(0, 1);
for (int i = X.size() - 1; i >= 0; i--)
A.push_back(X[i] - '0');
for (int i = Y.size() - 1; i >= 0; i--)
B.push_back(Y[i] - '0');
vector<int> E = ADD(A, B);
for (int i = E.size() - 1; i >= 0; i--)
cout << E[i];
return;
}
if (X[0] == '-')
{
X.erase(0, 1);
for (int i = X.size() - 1; i >= 0; i--)
A.push_back(X[i] - '0');
for (int i = Y.size() - 1; i >= 0; i--)
B.push_back(Y[i] - '0');
vector<int> E = ADD(A, B);
cout << '-';
for (int i = E.size() - 1; i >= 0; i--)
cout << E[i];
return;
}
}
int main()
{
string a, b;
cin >> a >> b;
if (a[0] == ‘-‘ || b[0] == ‘-‘)
{
Count(a, b);
return 0;
}
vector<int> A, B;
for (int i = a.size() - 1; i >= 0; i--)
A.push_back(a[i] - '0');
for (int i = b.size() - 1; i >= 0; i--)
B.push_back(b[i] - '0');
if (PAN(A, B))
{
vector<int> E = Sub(A, B);
for (int i = E.size() - 1; i >= 0; i--)
cout << E[i];
}
else
{
vector<int> E = Sub(B, A);
cout << '-';
for (int i = E.size() - 1; i >= 0; i--)
cout << E[i];
}
return 0;
}