UVA424 Integer Inquiry
一道高精度加法运算,原来做过两道相似的。不过看了书之后还是尝试用了一下模板,套用标准C还是出现了一点问题。加法函数的时候竟然会把全局定义的结构变量值清空。
题目:
Integer Inquiry
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<stdio.h> 2 #include<string.h> 3 struct bign 4 { 5 int len; 6 int s[200]; 7 }; 8 int max(int a,int b) 9 { 10 return (a>b)?a:b; 11 } 12 struct bign res,a; 13 char str[200]; 14 void change(char *str) 15 { 16 a.len=strlen(str); 17 int i; 18 for(i=0;i<a.len;i++) 19 a.s[i]=str[a.len-i-1]-'0'; 20 } 21 void plus(bign *res,bign *a) 22 { 23 int g,i; 24 for(i=0,g=0;g||i<max(res->len,a->len);i++) 25 { 26 int x=g; 27 if(i<res->len) 28 x+=res->s[i]; 29 if(i<a->len) 30 x+=a->s[i]; 31 res->s[i]=x%10; 32 g=x/10; 33 } 34 res->len=i; 35 } 36 int main() 37 { 38 memset(res.s,0,sizeof(res.s)); 39 while(scanf("%s",str)!=EOF) 40 { 41 if(strcmp(str,"0")==0) 42 { 43 int i; 44 for(i=res.len-1;i>=0;i--) 45 printf("%d",res.s[i]); 46 printf("\n"); 47 break; 48 } 49 else 50 { 51 change(str); 52 plus(&res,&a); 53 } 54 } 55 }