C编程实现两个字符串正整数相加

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

char* addBitInt(const char* num1, const char* num2)
{
	int c = 0; //进位,开始最低进位为0

	int length1 = strlen(num1);
	int length2 = strlen(num2);

	int i = length1 - 1;   //指向第一个加数的最低位
	int j = length2 - 1;   //指向第二个加数的最低位

	//得到2个数中较大的位数
	int maxLength = length1 >= length2 ? length1 + 1 : length2 + 2; 

	char* rst = (char*)malloc(maxLength + 1); //保存结果

	memset(rst, 0, maxLength + 1);

	int k;

	if (rst == NULL)
	{
		printf("malloc error\n");
		exit(1);
	}

	rst[maxLength] = '\0'; //字符串最后一位为'\0'
	k = maxLength - 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';

	return rst;
}


int main()
{
	char num1[] = "54678";
	char num2[] = "37894";

	char* buffer = addBitInt(num1, num2);
	cout << buffer << endl;

	free (buffer);

	system("pause");
	return 0;
}
发布了55 篇原创文章 · 获赞 1 · 访问量 3794

猜你喜欢

转载自blog.csdn.net/lpl312905509/article/details/104085961