超长位数的字符数的加法:
测试用例:112233445566778899 + 998877665544332211 = 1111111111111111110
程序代码:
1 #include <stdio.h> 2 #include <string.h> 3 #include <malloc.h> 4 #define MAXLEN 100 5 6 void add(char * a,char * b,char * c) 7 { 8 int i,j; 9 int sa = strlen(a); 10 int sb = strlen(b); 11 int max = sa>sb ? sa : sb; 12 int * s = (int *)malloc(sizeof(int) * (max + 1));//为保证运算和的不溢出,应是最长操作数的位数+1,范围是[0,max]; 13 int * A = (int *)malloc(sizeof(int) * max); 14 int * B = (int *)malloc(sizeof(int) * max); 15 16 for(i=0;i<max;i++) 17 A[i] = B[i] = s[i] = 0; //先初始化为0,防止高位相加时对应位不存在导致的问题 18 s[max] = 0; 19 20 for(i=0;i<sa;i++) //将a倒置以便低位对齐相加 21 A[i] = a[sa - i - 1] - '0'; 22 23 for(i=0;i<sb;i++) 24 B[i] = b[sb - i - 1] - '0'; 25 26 for(i=0;i<max;i++) 27 s[i] = A[i] + B[i]; 28 29 for(i=0;i<max;i++) //集中处理进位问题 30 { 31 if(s[i]>=10) // 若i = max-1时有进位,则s[max] != 0 32 { 33 s[i+1] += s[i] / 10; 34 s[i] %= 10; 35 } 36 } 37 38 if(s[max] != 0) //最高位有进位数据范围为[0,max] 39 { 40 for(j=0;j<=max;j++) 41 { 42 c[j] = s[max - j] + '0'; 43 } 44 c[max+1] = '