大数运算的加法和减法

#include
using namespace std;
const int base = 10000;
const int maxlen = 50 + 1;
void charTobignum(char *ch, int *bignum)
{

	int len, i, j, p, num;
	memset(bignum, 0, sizeof(int)*maxlen);
	len = strlen(ch);
	bignum[0] = len % 4 == 0 ? len / 4 : len / 4 + 1;
	i = 1;
	while (i <= len / 4)
	{
		num = 0;
		p = len - 4 * i;
		for (j = 1; j <= 4; j++)
			num = num * 10 + (ch[p++] - '0');
		bignum[i] = num;
		i++;
	}
	if (len % 4 != 0)
	{
		num = 0;
		for (i = 0; i <= len % 4 - 1; i++)
			num = num * 10 + (ch[i] - '0');
		bignum[len / 4 + 1] = num;
	}
}
void addtion(int *bignum1, int *bignum2, int *bignum_ans)
{
	int carry = 0;
	memset(bignum_ans, 0, sizeof(int)*maxlen);
	bignum_ans[0] = bignum1[0] > bignum2[0] ? bignum1[0] : bignum2[0];
	for (int pos = 1; pos <= bignum_ans[0]; pos++)
	{
		carry += bignum1[pos] + bignum2[pos];
		bignum_ans[pos] = carry % base;
		carry /= base;
	}
	if (carry)
		bignum_ans[++bignum_ans[0]] = carry;
}
int bignumcmp(int *bignum1, int *bignum2)
{
	if (bignum1[0] - bignum2[0])
		return bignum1[0] - bignum2[0];
	for (int pos = bignum1[0]; pos > 0;pos--)
	if (bignum1[pos] - bignum2[pos])
		return bignum1[pos] - bignum2[pos];
	return 0;
}
void subtract(int *bignum1, int *bignum2, int *bignum_ans)
{
	int borrow = 0;
	memset(bignum_ans, 0, sizeof(int)* maxlen);
	bignum_ans[0] = bignum1[0];
	for (int pos = 1; pos <= bignum_ans[0]; pos++)
	{
		bignum_ans[pos] = bignum1[pos] - borrow - bignum2[pos];
		if (bignum_ans[pos] < 0)
		{
			bignum_ans[pos] += base;
			borrow = 1;

		}
		else
		{
			borrow = 0;
 		}
	}
	while (!bignum_ans[bignum_ans[0]])--bignum_ans[0];
	if (bignum_ans[0] <= 0)
		bignum_ans[0] = 1;


}
void  printbignum(int *bignum)
{
	int *p = *bignum + bignum;
	cout << *p--;
	cout.fill('0');
	while (p > bignum)
	{
		cout.width(4);
		cout << *p--;
	}
		cout << endl;
	}
	int main()
	{
		int bignum1[maxlen], bignum2[maxlen], bignum_result[maxlen];
		char numstr[maxlen];
		cout << "请输入第一个大整数: ";
		cin >> numstr;
		charTobignum(numstr, bignum1);
		cout << "请输入第二个大整数: ";
		cin >> numstr;
		charTobignum(numstr, bignum2);
		addtion(bignum1, bignum2, bignum_result);
		cout << "两个大整数的和是: ";
		printbignum(bignum_result);
		if (bignumcmp(bignum1, bignum2) >= 0)
		{
			subtract(bignum1, bignum2, bignum_result);
			cout << "两个大整数的差是: ";
			printbignum(bignum_result);


		}
		else
		{
			subtract(bignum2, bignum1, bignum_result);
			cout << "两个大整数的差是: - ";
			printbignum(bignum_result);

		}
		return 0;
	
}
 

你可能感兴趣的:(大数运算的加法和减法)