1.大数相加
源码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 200
void bigNumPlus(const char *a, const char *b, char *c)
{
int na[N];
int nb[N];
int nc[N];
memset(na, 0, N * sizeof(int));
memset(nb, 0, N * sizeof(int));
memset(nc, 0, N * sizeof(int));
int lena = strlen(a);
int lenb = strlen(b);
for(int i=0; i<lena; i++)
na[i] = a[lena - 1 - i] - '0';
for(int i=0; i<lena; i++)
nb[i] = b[lenb - 1 - i] - '0';
int k = 0,i;
for(i = 0; i<lena || i<lenb; i++)
{
int tmp = na[i] + nb[i] + k;
k = tmp / 10;
nc[i] = tmp % 10;
}
if(k != 0)
nc[i++] = k;
int lenc = i;
for(i = 0; i<lenc; i++)
c[i] = nc[lenc - 1 - i] + '0';
c[i] = 0;
}
测试:
int main()
{
char a[] = "123456";
char b[] = "111711";
char c[N];
bigNumPlus(a, b, c);
printf("%s + %s = %s\n",a,b,c);
return 0;
}
结果: