两个大数相加_基于字符串的解决方案

# include <iostream>
# include <string>
using namespace std;

void BigNumbersPlus(char* num1, char* num2)
{
	char* sum = new char[SIZE_MAX + 2];
	int len1 = strlen(num1);
	int len2 = strlen(num2);
	int maxlen = len1 > len2 ? len1 : len2;

	char* temp1 = new char[maxlen + 1];
	char* temp2 = new char[maxlen + 1];
	memset(temp1, '0', maxlen); temp1[maxlen] = '\0';
	memset(temp2, '0', maxlen); temp2[maxlen] = '\0';

	int nsum = 0;
	int isCarryBit = 0;
	int isOverflow = 0;
	//反转字符串 对齐
	int i = 0, j = 0;
	for (i = len1 - 1; i >= 0; i--)
	{
		temp1[j++] = num1[i];
	}
	temp1[j] = '\0';
	j = 0;
	for (i = len2 - 1; i >= 0; i--)
	{
		temp2[j++] = num2[i];
	}
	temp2[j] = '\0';
	//字符串相加从低位到高位
	for (i = 0; i < maxlen; i++)
	{
		nsum = temp1[i] - '0' + temp2[i] - '0' + isCarryBit;
		//是否有进位
		if (nsum > 9)
		{
			if (i == maxlen - 1)
			{
				isOverflow = 1; //溢出
			}
			sum[i] = nsum - 10 + '0';
			isCarryBit = 1;
		}
		else{
			isCarryBit = 0;
			sum[i] = nsum + '0';
		}
	}
	if (isOverflow == 1)
	{
		sum[maxlen++] = '0' + isCarryBit;
	}
	sum[maxlen] = '\0';
	///反转打印结果
	for (i = maxlen - 1; i >= 0; i--)
	{
		cout << sum[i];
	}
	cout << endl;
	delete [] temp1;
	delete [] temp2;
	delete [] sum;
}

int main()
{
	char* num1 = new char[SIZE_MAX + 1];
	char* num2 = new char[SIZE_MAX + 1];
	cout << "please input a number:" << endl;
	gets(num1);
	cout << "please input another number" << endl;
	gets(num2);
	BigNumbersPlus(num1, num2);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/shenziheng1/article/details/80065446