string sum(string s1,string s2)
{
if(s1.length()<s2.length())
{
string temp=s1;
s1=s2;
s2=temp;
} //判断并max s1,s2的值
int i,j;
for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--)
{
s1[i]=char(s1[i]+(j>=0?s2[j]-'0':0)); //注意细节,如果超出s2的长度就+0
if(s1[i]-'0'>=10)
{
s1[i]=char((s1[i]-'0')%10+'0');
if(i) s1[i-1]++;
else s1='1'+s1;//这句话确保了形如1+99这类情况的正确性
}
}
return s1;
}
练习题:
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
string sum(string s1,string s2)
{
if(s1.length()<s2.length())
{
string temp=s1;
s1=s2;
s2=temp;
}
int i,j;
for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--)
{
s1[i]=char(s1[i]+(j>=0?s2[j]-'0':0)); //注意细节
if(s1[i]-'0'>=10)
{
s1[i]=char((s1[i]-'0')%10+'0');
if(i) s1[i-1]++;
else s1='1'+s1;
}
}
return s1;
}
int main()
{
int test,k=1;
string a,b;
cin>>test;
while(test--)
{
cin>>a>>b;
cout<<"Case "<<k++<<":"<<endl;
cout<<a<<" + "<<b<<" = "<<sum(a,b)<<endl;
if(test)cout<<endl;
}
return 0;
}