您的位置:首页 > 其它

无线OSS-高精度整数加法(加数可以为负数,应实现高精度加减法)

2017-06-13 18:47 239 查看
#include<bits/stdc++.h>
using namespace std;
bool cmp(string a,string b)
{
if(a.size()>b.size())return true;
if(a.size()<b.size())return false;
if(a<=b)return false;
return true;
}
string add(string a,string b)
{
int x,y,c=0;
string ab;
for(int i=a.size()-1,j=b.size()-1; i>=0||j>=0; i--,j--)
{
x=i>=0?a[i]-'0':0;
y=j>=0?b[j]-'0':0;
ab+=(x+y+c)%10+'0';
c=(x+y+c)/10;
}
if(c==1)ab+='1';
reverse(ab.begin(),ab.end());
return ab;
}
string sub(string a,string b)
{
int x,y,c=0;
string ab;
for(int i=a.size()-1,j=b.size()-1; i>=0||j>=0; i--,j--)
{
x=i>=0?a[i]-'0':0;
y=j>=0?b[j]-'0':0;
if(x<y)
{
ab+=x+10-y+'0';
for(int k=i-1; k>=0; k--)
{
if(a[k]>'0')
{
a[k]=a[k]-1;
break;
}
else
{
a[k]='9';
}
}
}
else
{
ab+=x-y+'0';
}
}
reverse(ab.begin(),ab.end());
int i;
for(i=0; i<ab.size(); i++)
if(ab[i]!='0')break;
if(i==ab.size())return "0";
return ab.substr(i,ab.size()-i);
}
int main()
{
string a,b;
while(cin>>a>>b)
{
if(a[0]!='-'&&b[0]!='-')
{
cout<<add(a,b)<<endl;
}
else if(a[0]=='-'&&b[0]=='-')
{
cout<<"-"<<add(a.substr(1,a.size()-1),b.substr(1,b.size()-1))<<endl;
}
else
{
string a1,b1;
if(a[0]=='-')
{
a1=a.substr(1,a.size()-1);
b1=b.substr(0,b.size());
}
else
{
a1=b.substr(1,b.size()-1);
b1=a.substr(0,a.size());
}
if(cmp(a1,b1))
{
cout<<"-"<<sub(a1,b1)<<endl;
}
else
{
cout<<sub(b1,a1)<<endl;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法
相关文章推荐