Base time limit: 1 second space limit: 131072 KB score: 0 Difficulty: basic question
Two large integers a and B are given, and the result of A+B is calculated.
Input
Line 1: large A Line 2: large B (the length of a and B is less than 10000. Note: A and B may be negative.)
Output
Output A + B
Input example
68932147586 468711654886
Output example
537643802472
It's OK to directly set the template of addition and subtraction of large numbers. Here is A place to pay attention to, because A and B may be negative numbers. Consider that A is negative and B is positive. B is negative and A is positive. Both are negative. Three special cases. Because the large subtraction template is suitable for large subtraction and small subtraction, all three special cases should be judged.
#include <cstring> #include <string> #include <algorithm> #include <cstdio> #include <iostream> using namespace std; const int L = 20010; string add(string a, string b){ string ans; int na[L] = {0}, nb[L] = {0}; int la = a.size(), lb = b.size(); for(int i = 0; i < la; i++) na[la-1-i] = a[i] - '0'; for(int i = 0; i < lb; i++) nb[lb-1-i] = b[i] - '0'; int lmax = la > lb ? la : lb; for(int i = 0; i < lmax; i++){ na[i] += nb[i]; na[i+1] += na[i]/10; na[i] %= 10; } if(na[lmax]) lmax++; for(int i = lmax-1; i >= 0;i--) ans += na[i] + '0'; return ans; } string sub(string a, string b){ string ans; int na[L] = {0},nb[L] = {0}; int la = a.size(), lb = b.size(); for(int i = 0; i< la; i++) na[la-1-i] = a[i] - '0'; for(int i=0; i < lb; i++) nb[lb-1-i] = b[i] - '0'; int lmax = la > lb ? la : lb; for(int i = 0; i < lmax; i++){ na[i] -= nb[i]; if(na[i] < 0) na[i] += 10,na[i+1]--; } while(!na[--lmax] && lmax > 0); lmax++; for(int i = lmax-1; i >= 0; i--) ans += na[i] + '0'; return ans; } int main(){ string a,b; while(cin>>a>>b){ bool flag=false; if(a[0] == '-' && b[0] != '-'){ a.erase(a.begin()); flag = true; if(a.size() > b.size()){ cout<<'-'<<sub(a,b)<<endl; } else if(a.size() < b.size()){ cout<<sub(b,a)<<endl; } else if(a.size() == b.size() && a < b){ cout<<sub(b,a)<<endl; } else if(a.size() == b.size() && a > b){ cout<<'-'<<sub(a,b)<<endl; } } if(b[0] == '-' && a[0] != '-'){ b.erase(b.begin()); flag = true; if(b.size() > a.size()){ cout<<'-'<<sub(b,a)<<endl; } else if(b.size() < a.size()){ cout<<sub(a,b)<<endl; } else if(a.size() == b.size() && b < a){ cout<<sub(a,b)<<endl; } else if(a.size() == b.size() && b > a){ cout<<'-'<<sub(b,a)<<endl; } } if(a[0] =='-' && b[0] =='-'){ a.erase(a.begin()); b.erase(b.begin()); flag = true; cout<<'-'<<add(a,b)<<endl; } if(a[0] !='-' && b[0] != '-' && !flag){ cout<<add(a,b)<<endl; } } return 0; }