大数的加法

     大树的加法,实则用数组去进行处理。将两个数的每位相加的结果先保存在整形数组中,然后逐位进行结果的转换。代码如下
#include "stdio.h"
#include<string.h>

int max(int x,int y)
{
	if (x>y)
		return x;
	else
		return y;
}
int main()
{
	int a[510]={0}, b[510]={0}, c[510]={0};
	int m, n, i, p, j;
	char str1[510], str2[510];
	while (scanf("%s %s",str1,str2) == 2)
	{
		m= strlen(str1);
		n= strlen(str2);
		p= max(m,n);
		for (i=0; i<p; i++)
		{
			a[m-1-i] = str1[i]- 48;
			b[n-1-i] = str2[i]- 48;
		}
		for (j=0; j<p; j++)
		{
			c[j] = a[j] + b[j];
		}
		for (i=0; i <p; i++)
		{
			c[i+1]= c[i]/10 +c[i+1];
			c[i]= c[i]%10;
		}
		if (c[p]==0)
		{
			for (i=p-1; i>=0; i--)
				printf("%d",c[i]);
		}
		else
		{
			for (i= p; i>=0; i--)
				printf("%d",c[i]);
		}
		printf("\n");
	}
	return 0;
}

posted @ 2015-05-19 17:44  Tovi  阅读(133)  评论(0编辑  收藏  举报