求两个大整数相加。
记录一下高精度的模板
题目:
Integer Inquiry |
One of the first users of BIT's new supercomputer was Chip Diller. He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
``This supercomputer is great,'' remarked Chip. ``I only wish Timothy were here to see these results.'' (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.)
Input
The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative).
The final input line will contain a single zero on a line by itself.
Output
Your program should output the sum of the VeryLongIntegers given in the input.
Sample Input
123456789012345678901234567890 123456789012345678901234567890 123456789012345678901234567890 0
Sample Output
370370367037037036703703703670
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <malloc.h> 5 #include <memory.h> 6 using namespace std; 7 8 const int maxn =1000; 9 struct bign 10 { 11 int len,s[maxn]; 12 bign(){memset(s,0,sizeof(s));len=1;} 13 14 bign(int num){*this = num;} 15 bign(const char*num){*this=num;} 16 17 18 bign operator = (int num) 19 { 20 char s[maxn]; 21 sprintf(s,"%d",num); 22 *this = s; 23 return *this; 24 } 25 26 27 bign operator = (const char* num) 28 { 29 len=strlen(num); 30 for(int i=0;i<len;i++) s[i]=num[len-i-1]-'0'; 31 return *this; 32 } 33 34 bign operator + (const bign& b) const 35 { 36 bign c; 37 c.len=0; 38 39 for(int i=0,g=0;g||i<max(len,b.len);i++) 40 { 41 int x=g; 42 if(i<len) x+=s[i]; 43 if(i<b.len)x+=b.s[i]; 44 c.s[c.len++] = x%10; 45 g=x/10; 46 } 47 return c; 48 } 49 50 51 string str() const 52 { 53 string res=""; 54 for(int i=0;i<len;i++)res=(char)(s[i]+'0')+res; 55 if(res=="")res="0"; 56 return res; 57 } 58 59 bool operator <(const bign& b)const 60 { 61 if(len!=b.len)return len<b.len; 62 for(int i=len-1;i>=0;i--) 63 if(s[i]!=b.s[i])return s[i]<b.s[i]; 64 return false; 65 66 } 67 bool operator != (const bign& b)const {return b<*this ||*this<b;} 68 69 70 }; 71 72 73 istream& operator >>(istream &in,bign& x) 74 { 75 string s; 76 in>>s; 77 x=s.c_str(); 78 return in; 79 80 } 81 ostream& operator << (ostream &out,const bign& x) 82 { 83 out<<x.str(); 84 return out; 85 } 86 87 88 int main() 89 { 90 bign a,b; 91 bign ans=0; 92 cin>>a; 93 while(a!=0) 94 { 95 ans=ans+a; 96 cin>>a; 97 98 } 99 cout<<ans<<endl; 100 101 102 }