首先因爲我自己的馬虎,總是錯,新手總是以各種原因錯,可能是馬虎i打成了j,或者少加了=,少考慮的情況,總之路漫漫其修遠兮,都沒刷夠1000道題,算什麼熱愛。
int是三十二位,大數相加很容易溢出,所以要用char,int總是限制在一定數內,long long int 也如此,但char字符串明顯可以存更多的數。
用char存儲大數後,將各個位存在int數組裏面,各個數相加,k爲進位運算,最後因爲字符串存入數組時下標是 0,1,2,3,4,,,,但是我們正常大數輸出順序爲n,n-1,,,4,3,2,1,0,所以要倒着輸出。
模板代碼:
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
int q[10000],w[10000];
char s1[10000],s2[10000];
cin>>s1>>s2;
int a=strlen(s1);
int b=strlen(s2);
int i=0,j=0,smax;
while(a-1-i>=0)
{
q[i]=s1[a-1-i]-'0';
i++;
}
while(b-1-j>=0)
{
w[j]=s2[b-1-j]-'0';
j++;
}
if(a>=b)smax=a;
else smax=b;
int add[smax]={0};
int k=0;
for(int i=0;i<smax;i++)
{
add[i]=(q[i]+w[i]+k)%10;
k=(q[i]+w[i]+k)/10;
}
if(k>0)
{
smax=1;
cout<<smax;
}
for(int i=smax-1;i>=0;i--)
{
cout<<add[i];
}
cout<<endl;
}