#include <iostream>
#include <string>
using namespace std;
string add(const string& a,const string& b)
{
string result; //用于记录计算结果
int len_a = a.length() - 1;
int len_b = b.length() - 1;
int carry = 0; //进位
for(;len_a>=0 && len_b>=0;len_a--,len_b--)
{
int t = (a[len_a] - '0') + (b[len_b] - '0') + carry;
carry = t/10;
t %= 10;
result += char(t+'0');
}
for(;len_a>=0;len_a--)
{
int t = (a[len_a] - '0') + carry;
carry = t/10;
t %= 10;
result += char(t+'0');
}
for(;len_b>=0;len_b--)
{
int t = (b[len_b] - '0') + carry;
carry = t/10;
t %= 10;
result += char(t+'0');
}
if(carry != 0)
{
result += char(carry+'0');
}
//反转
int len_r = result.length();
for(int i = 0;i<len_r/2;i++)
{
char temp = result[i];
result[i] = result[len_r-i-1];
result[len_r-i-1] = temp;
}
return result;
}
string sub(const string& a,const string& b)
{
string result; //用于记录计算结果
string big;
string small;
int len_a = a.length();
int len_b = b.length();
int borrow = 0; //借位
int sign = 1; //符号位
if(len_a < len_b)
{
sign = -1;
big = b;
small = a;
}
else if(len_a == len_b && a.compare(b)<0)
{
sign = -1;
big = b;
small = a;
}
else
{
big = a;
small = b;
}
//big - small
len_a = big.length() - 1;
len_b = small.length() - 1;
for(;len_a>=0 && len_b>=0;len_a--,len_b--)
{
int t = big[len_a] - small[len_b] - borrow;
borrow = (t >= 0) ? 0 : 1;
if(t < 0)
{
t += 10;
}
result += char(t+'0');
}
for(;len_a>=0;len_a--)
{
int t = big[len_a] - '0'- borrow;
borrow = (t >= 0) ? 0 : 1;
if(t < 0)
{
t += 10;
}
result += char(t+'0');
}
int len_r = result.length();
for(int i = 0;i<len_r/2;i++)
{
char temp = result[i];
result[i] = result[len_r-i-1];
result[len_r-i-1] = temp;
}
string r;
if(sign == -1)
{
r += '-';
}
for(int i = 0;i<len_r;i++)
{
if(result[i] != '0')
{
r += result.substr(i);
break;
}
}
return r;
}
string GetSubResult(const string& a,const string& b)
{
string result;
string aa = a;
string bb = b;
if(a[0] != '-' && b[0] == '-')//a - -b = a+b
{
bb = b.substr(1);
result = add(aa, bb);
}
else if(a[0] == '-' && b[0] != '-')//-a - b = -(a+b)
{
aa = a.substr(1);
result = '-' + add(aa, bb);
}
else if(a[0] == '-' && b[0] == '-')//-a - -b = b - a
{
aa = a.substr(1);
bb = b.substr(1);
result = sub(bb, aa);
}
else
{
result = sub(aa, bb);
}
return result;
}
int main()
{
string a, b;
cin>>a>>b;
cout<<GetSubResult(a, b)<<endl;
return 0;
}
转载于:https://www.cnblogs.com/hbf369/archive/2012/09/21/2697595.html