超长位数的字符数的加法与乘法

来源:互联网 发布:war包解析源码 编辑:程序博客网 时间:2024/04/30 07:45

超长位数的字符数的加法:

测试用例:112233445566778899 + 998877665544332211 = 1111111111111111110

程序代码:

#include <stdio.h>#include <string.h>#include <malloc.h>#define MAXLEN 100void add(char * a,char * b,char * c){    int i,j;int sa = strlen(a);int sb = strlen(b);int max = sa>sb ? sa : sb;int * s = (int *)malloc(sizeof(int) * (max + 1));//为保证运算和的不溢出,应是最长操作数的位数+1,范围是[0,max];int * A = (int *)malloc(sizeof(int) * max);int * B = (int *)malloc(sizeof(int) * max);for(i=0;i<max;i++)A[i] = B[i] = s[i] = 0;//先初始化为0,防止高位相加时对应位不存在导致的问题s[max] = 0;for(i=0;i<sa;i++)//将a倒置以便低位对齐相加A[i] = a[sa - i - 1] - '0';for(i=0;i<sb;i++)B[i] = b[sb - i - 1] - '0';for(i=0;i<max;i++)s[i] = A[i] + B[i];for(i=0;i<max;i++)//集中处理进位问题{if(s[i]>=10)// 若i = max-1时有进位,则s[max] != 0{s[i+1] += s[i] / 10;s[i] %= 10;}}if(s[max] != 0)//最高位有进位数据范围为[0,max]{for(j=0;j<=max;j++){c[j] = s[max - j] + '0';}c[max+1] = '\0';}else//最高位无进位,数据范围为[0,max-1]{for(j=0;j<max;j++){c[j] = s[max -1 - j] + '0';}c[max] = '\0';}free(A);free(B);free(s);}int main(){char a[MAXLEN];char b[MAXLEN];char c[2 * MAXLEN];while(scanf("%s + %s",a,b) != EOF){add(a,b,c);printf("%s + %s = ",a,b);puts(c);}return 0;}

超长位数的字符数的乘法:

测试用例:112233445566778899 * 998877665544332211 = 112107482103740987777903741240815689

程序代码:

#include <stdio.h>#include <string.h>#include <malloc.h>#define MAXLEN 100void multiply(char * a,char * b,char * c){    int i,j,ca,cb,* s;    ca = strlen(a);//a操作数的位数    cb = strlen(b);//b操作数的位数    s = (int*)malloc(sizeof(int)*(ca+cb));//s指向能够存储a和b的空间    for (i=0;i<ca+cb;i++)    s[i] = 0;//初始化s数组元素全为0    for (i=0;i<ca;i++)    for (j=0;j<cb;j++)    s[i+j+1] += (a[i]-'0') * (b[j]-'0');    for (i=ca+cb-1;i>=0;i--)    if (s[i]>=10)    {        s[i-1] += s[i]/10;//高位加上低位的进位        s[i] %= 10;        }    i=0;    while (s[i]==0)    i++;   for (j=0;i<ca+cb;i++,j++)   c[j] = s[i] + '0';    c[j]='\0';    free(s);}int main(){char a[MAXLEN];char b[MAXLEN];char c[2 * MAXLEN];while(scanf("%s * %s",a,b) != EOF){multiply(a,b,c);printf("%s * %s = ",a,b);puts(c);}return 0;}


0 0
原创粉丝点击