先交换,再补全,再逐步相加
下面是我参考萌哒哒的柳婼的,还有附上我16分的代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
char s[13]={'0','1','2','3','4','5','6','7','8','9','J','Q','K'};
string a,b,c;
//freopen("1048.txt","r",stdin);
cin>>a>>b;
int len1=a.length(),len2=b.length();
int x;string ans="";
for(int i=0;i<=len1/2-1;i++)
swap(a[i],a[len1-1-i]);
for(int i=0;i<=len2/2-1;i++)
swap(b[i],b[len2-1-i]);
if(len1>len2)
b.append(len1-len2,'0');
else
a.append(len2-len1,'0');
for(int i=0;i<a.length();i++)
{
if((i+1)%2)
{
x=a[i]-'0'+b[i]-'0';
ans+=s[x%13];
}
else
{
x=b[i]-a[i]+10;
ans+=s[x%10];
}
}
for(int i=ans.length()-1;i>=0;i--)
cout<<ans[i];
return 0;
}
#include<bits/stdc++.h>
using namespace std;
string add(string s1,string s2)
{
string ans="";int num,Long,Short;
int flag1=0,flag2=0;
int len1=s1.length(),len2=s2.length();
reverse(s1.begin(),s1.end());
reverse(s2.begin(),s2.end());
if(len1>len2)
{
Long=len1;Short=len2;
flag1=1;
}
else
{
Long=len2;Short=len1;
flag2=1;
}
for(int i=0;i<Long;i++)
{
if(i<Short)
{
if((i+1)%2)
{
num=s1[i]+s2[i]-'0'-'0';
num%=13;
}
else
{
num=s2[i]-s1[i]+10;
num%=10;
}
}
else
{
if(flag1)
num=s1[i]-'0';
if(flag2)
num=s2[i]-'0';
}
if(num>9)
{
if(num==10)
ans+='J';
if(num==11)
ans+='Q';
if(num==12)
ans+='K';
}
else
ans+=char(num+'0');
}
reverse(ans.begin(),ans.end());
return ans;
}
int main()
{
string s1,s2,ans;
//freopen("1048.txt","r",stdin);
cin>>s1>>s2;
ans=add(s1,s2);
int len=ans.length(),i;
for(i=0;i<len;i++)
{
if(ans[i]!='0')
break;
}
if(i==len)
cout<<"0";
else
{
for(int k=i;k<len;k++)
cout<<ans[k];
}
return 0;
}