大数加法模拟
https://codeforces.com/contest/1181/problem/B
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 string cal(string a,string b)//字符串加法,模拟数的加法即可 5 { 6 string ans=""; 7 int pos1=a.size()-1,pos2=b.size()-1; 8 int last=0,x=0; 9 while(1){ 10 if(pos1<0&&pos2<0)break; 11 if(pos1<0&&pos2>=0){ 12 while(pos2>=0){ 13 x=b[pos2--]-'0'+last; 14 if(x>=10){ 15 last=x/10; 16 x%=10; 17 } 18 else 19 last=0; 20 ans+=x+'0'; 21 } 22 break; 23 } 24 if(pos2<0&&pos1>=0){ 25 while(pos1>=0){ 26 x=a[pos1--]-'0'+last; 27 if(x>=10){ 28 last=x/10; 29 x%=10; 30 } 31 else 32 last=0; 33 ans+=x+'0'; 34 } 35 break; 36 } 37 x=a[pos1--]-'0'+b[pos2--]-'0'+last; 38 if(x>=10){ 39 last=x/10; 40 x%=10; 41 } 42 else 43 last=0; 44 ans+=x+'0'; 45 } 46 if(last) 47 ans+=last+'0'; 48 return ans; 49 } 50 int main() 51 { 52 int n; 53 cin>>n; 54 string s; 55 cin>>s; 56 int pos1=n/2,pos2=n/2+1; 57 // printf("pos1:%d pos2:%d\n",pos1,pos2); 58 while(s[pos1]=='0'&&pos1>0)pos1--; 59 while(s[pos2]=='0'&&pos2<n-1)pos2++; 60 61 string a=s.substr(0,pos1); 62 // cout<<a<<endl; 63 string b=s.substr(pos1,s.size()); 64 string ans=cal(a,b); 65 // cout<<ans<<endl; 66 reverse(ans.begin(),ans.end()); 67 // cout<<ans<<endl; 68 string aa=s.substr(0,pos2); 69 string bb=s.substr(pos2,s.size()); 70 string anss=cal(aa,bb); 71 reverse(anss.begin(),anss.end()); 72 if(s[pos2]=='0'){//特判后一部分不能分的情况,如果想到的话,这个题比赛的时候就能做出来了丫丫丫 73 // printf("haha\n"); 74 return cout<<ans<<endl,0; 75 } 76 if(ans.size()<anss.size())cout<<ans<<endl; 77 else if(ans.size()>anss.size())cout<<anss<<endl; 78 else{ 79 if(ans<anss) 80 cout<<ans<<endl; 81 else 82 cout<<anss<<endl; 83 } 84 return 0; 85 }