1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 char* BigIntegerAdd(char *s1,int n1,char *s2,int n2) 5 { 6 char *result,*p1,*p2; 7 int c1=n1,c2=n2,length=n1>n2?n1:n2,carry=0; 8 9 p1=s1; 10 p2=s2; 11 result=(char *)malloc((length+1)*sizeof(char)); 12 13 //make p1,p2,result point to tail 14 p1=s1+n1-1; 15 p2=s2+n2-1; 16 result+=length; 17 *(result+1)=0; //mark the end of string 18 while (p1>=s1 && p2>=s2) 19 { 20 if(*p1+*p2+carry-48>57)//有进位 21 { 22 *result=*p1+*p2+carry-10-48; 23 carry=1; 24 } 25 else 26 { 27 *result=*p1+*p2+carry-48; 28 carry=0; 29 } 30 p1--; 31 p2--; 32 result--; 33 } 34 35 //剩余一串的处理 36 if (p1<s1) 37 { 38 while (p2>=s2) 39 { 40 if (*p2+carry>57) 41 { 42 *result=*p2+carry-10; 43 carry=1; 44 } 45 else 46 { 47 *result=*p2+carry; 48 carry=0; 49 } 50 p2--; 51 result--; 52 } 53 } 54 else 55 { 56 while (p1>=s1) 57 { 58 if (*p1+carry>57) 59 { 60 *result=*p1+carry-10; 61 carry=1; 62 } 63 else 64 { 65 *result=*p1+carry; 66 carry=0; 67 } 68 p1--; 69 result--; 70 } 71 } 72 //最高位是否有进位 73 if (carry==1) 74 { 75 *result=carry+48; 76 } 77 else 78 { 79 result++; //最高位无进位,指针退一个 80 } 81 //puts(result); 82 return result; 83 } 84 void main() 85 { 86 87 int n,i=1; 88 char *s1=(char*)malloc(sizeof(char)*1000); 89 char *s2=(char*)malloc(sizeof(char)*1000); 90 scanf("%d",&n); 91 getchar(); 92 while (i<=n) 93 { 94 scanf("%s",s1); 95 scanf("%s",s2); 96 if (i==n) 97 { 98 printf("Case %d:\n%s + %s = %s\n",i,s1,s2,BigIntegerAdd(s1,strlen(s1),s2,strlen(s2))); 99 } 100 else 101 { 102 printf("Case %d:\n%s + %s = %s\n\n",i,s1,s2,BigIntegerAdd(s1,strlen(s1),s2,strlen(s2))); 103 } 104 105 i++; 106 } 107 }