编程实现任意长度的两个正整数相加 代码实现


char* addBigInt(char* num1,char* num2)
{
	int c = 0;//进位,开始最低进位为0
	int i = strlen(num1)-1;
	int j = strlen(num2)-1;
	int maxLength = strlen(num1) >= strlen(num2)?(strlen(num1)+1):(strlen(num2)+1);//得到两个数中较大数的位数
	char* rst = (char*)malloc(maxLength+1);//保存结果
	int k;
	if (rst==NULL)
	{
		printf("malloc eror!\n");
	
	}

	rst[maxLength] = '\0';//字符串最后一位为'\0'
	k = strlen(rst)-1; //指向结果数组的最低位
	while ((i>=0)&&(j>=0))
	{
		rst[k] = ((num1[i]-'0') + (num2[j]-'0')+c)%10+'\0';
		c = ( (num1[i]-'0') + (num2[j]-'0')+ c)/10;
		--i;
		--j;
		--k;
	}
	while (i>=0)
	{
		rst[k] = ((num1[i]-'0')+c)%10+'0';
		c = ((num1[i]-'0')+c)/10;
		--i;
		--k;
	}
	while (j>=0)
	{
		rst[k] = ((num2[j]-'0')+c)%10+'0';
		c = ((num2[j]-'0')+c)/10;
		--j;
		--k;
	}
	rst[0] = c+'0';
	if (rst[0]!='0')
	{
		return rst;

	}
	else
	{
		return rst+1;
	}

}



展开阅读全文

没有更多推荐了,返回首页