1 #include<stdio.h> 2 #include<string.h> 3 4 void reverse( char *s ) /*将字符串逆置*/ 5 { 6 int length; 7 int i = 0; 8 char temp; 9 length = strlen( s ); 10 while( i < length - i - 1 ) 11 { 12 temp = s[i]; 13 s[i] = s[length - i - 1]; 14 s[length - i - 1] = temp; 15 i++; 16 } 17 } 18 19 void AddBigNum( char* s1, char* s2, char* result ) 20 { 21 int len1 = strlen( s1 ); 22 int len2 = strlen( s2 ); 23 int acc = 0, temp, i; /*acc为进位标记*/ 24 if( s1 == NULL || s2 == NULL || result == NULL ) 25 { 26 return; 27 } 28 reverse( s1 ); 29 reverse( s2 ); 30 for( i = 0; i < len1 && i < len2; i++ ) 31 { 32 temp = s1[i] - \'0\' + s2[i] - \'0\' + acc; /*计算每位的实际和*/ 33 result[i] = temp % 10 + \'0\'; /*通过求余数来确定每位的最终值*/ 34 if( temp >= 10 ) /*通过这个if..else..条件来判断是否有进位,并设置进位值*/ 35 acc = 1; 36 else 37 acc = 0; 38 } 39 if( i < len1 ) /*两个加数位数不同*/ 40 { 41 for( ; i < len1; i++ ) 42 { 43 temp = s1[i] - \'0\' + acc; /*依旧要考虑进位,比如9999 + 1的情况*/ 44 result[i] = temp % 10 + \'0\'; 45 if( temp >= 10 ) 46 acc = 1; 47 else 48 acc = 0; 49 } 50 } 51 if( i < len2 ) 52 { 53 for( ; i < len2; i++ ) 54 { 55 temp = s2[i] - \'0\' + acc; 56 result[i] = temp % 10 + \'0\'; 57 if( temp >= 10 ) 58 acc = 1; 59 else 60 acc = 0; 61 } 62 } 63 64 if( acc == 1 ) /*考虑如:123 + 911 = 1034的情况,如果不增加这个条件会得到结果为034,进位被舍弃*/ 65 66 result[i++] = \'1\'; 67 68 result[i] = \'\0\'; 69 reverse( result ); 70 } 71 72 main() 73 { 74 char s1[100]; 75 char s2[100]; 76 char result[100]; 77 while((scanf("%s %s",&s1,&s2))!=EOF) 78 { 79 AddBigNum( s1, s2, result ); 80 printf( "%s\n", result ); 81 } 82 }