利用string的一些函数使得大数相加和相减变得简洁和对称,更加容易记忆,个人认为string比char好用多了,而且速度也不慢!
#include<iostream>
#include<string>
using namespace std;
string add(string a,string b)//大数相加
{
string ans="";
int temp=0,sum;
for(int i=a.length()-1,j=b.length()-1;i>=0||j>=0;i--,j--)
{
if(i<0)sum=b[j]-'0';
else if(j<0)sum=a[i]-'0';
else sum=a[i]-'0'+b[j]-'0';
sum+=temp;
temp=sum/10;
ans.insert(ans.begin(),sum%10+'0');
}
if(temp)ans.insert(ans.begin(),temp+'0');
return ans;
}
string jian(string a,string b)//大数相减,注:a,b无负号且a比b大,可以通过下面的comp函数比较
{
string ans="";
int temp=0,cha;
for(int i=a.length()-1,j=b.length()-1;i>=0||j>=0;i--,j--)
{
if(j>=0)cha=(a[i]-'0')-(b[j]-'0')-temp;
else cha=a[i]-'0'-temp;
if(cha<0)
{
cha+=10;
temp=1;
}
else temp=0;
ans.insert(ans.begin(),cha+'0');
}
while(ans[0]=='0')ans.erase(0,1);
return ans;
}
int comp(string a,string b)//比较a,b的大小,注:a,b无负号,a比b大返回1,小返回-1,一样大返回0
{
if(a.length()>b.length())return 1;
else if(a.length()<b.length())return -1;
else
{
int i=0;
while(a[i]==b[i]&&i<a.length())i++;
if(i==a.length())return 0;
else if(a[i]>b[i])return 1;
else return -1;
}
}
int main()
{
int t,que=1;
cin>>t;
while(t--)
{
string a,b,c,res="";
cin>>a>>b>>c;
if(a[0]!='-'&&b[0]!='-')//a,b都大于等于0
{
res=add(a,b);
}
else if(a[0]=='-'&&b[0]=='-')//a,b都小于0
{
a.erase(0,1);
b.erase(0,1);
res=add(a,b);
res.insert(res.begin(),'-');
}
else//a,b一正一负
{
if(a[0]=='-')//a负b正
{
a.erase(0,1);
int k=comp(a,b);
if(k==1)
{
res=jian(a,b);
res.insert(res.begin(),'-');
}
else if(k==0)res="0";
else if(k==-1)
{
res=jian(b,a);
}
}
else if(b[0]=='-')//b负a正
{
b.erase(0,1);
int k=comp(a,b);
if(k==1)
{
res=jian(a,b);
}
else if(k==0)res="0";
else if(k==-1)
{
res=jian(b,a);
res.insert(res.begin(),'-');
}
}
}
int ans,tag;
if(res[0]!='-'&&c[0]!='-')//a+b的结果和c进行比较
{
tag=comp(res,c);
if(tag==1)ans=1;
else ans=0;
}
else if(res[0]=='-'&&c[0]=='-')
{
res.erase(0,1);
c.erase(0,1);
tag=comp(res,c);
if(tag==-1)ans=1;
else ans=0;
}
else
{
if(res[0]=='-')ans=0;
else ans=1;
}
if(ans)cout<<"Case #"<<que++<<": true"<<endl;
else cout<<"Case #"<<que++<<": false"<<endl;
}
return 0;
}