大整数问题

1. 大整数相加

#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
#include <limits.h>
#include <ctype.h>

using namespace std;

char* add(const char *lhs, const char *rhs)
{
	if (lhs == NULL || rhs == NULL)
		return NULL;

	int lhsLength = strlen(lhs);
	int rhsLength = strlen(rhs);
	char *result = new char[max(lhsLength, rhsLength) + 1];
	int i = lhsLength - 1;
	int j = rhsLength - 1;
	int k = 0;
	int carry = 0;

	while (i >= 0 && j >= 0)
	{
		int numLhs = lhs[i] - '0';
		int numRhs = rhs[j] - '0';
		int sum = numLhs + numRhs + carry;

		if (sum >= 10)
		{
			sum -= 10;
			carry = 1;
			result[k++] = sum + '0';
		}
		else
		{
			carry = 0;
			result[k++] = sum + '0';
		}
		i--;
		j--;
	}

	while (i >= 0)
	{
		int sum = lhs[i] - '0' + carry;
		if (sum >= 10)
		{
			sum -= 10;
			carry = 1;
			result[k++] = sum + '0';
			i--;
		}
		else
		{
			carry = 0;
			result[k++] = sum + '0';
			i--;
		}
	}

	while (j >= 0)
	{
		int sum = rhs[j] - '0' + carry;
		if (sum >= 10)
		{
			sum -= 10;
			carry = 1;
			result[k++] = sum + '0';
			j--;
		}
		else
		{
			carry = 0;
			result[k++] = sum + '0';
			j--;
		}
	}

	result[k] = 0;
	reverse(result, result + k);

	return result;
}

void main()
{
	const char *lhs = "87695";
	const char *rhs = "498";

	char *result = add(lhs, rhs);
	if (result != NULL)
		cout << "sum = " << result << endl;
}

2. 大整数相乘

#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
#include <limits.h>
#include <ctype.h>

using namespace std;

char* multiply(const char *lhs, const char *rhs)
{
	if (lhs == NULL || rhs == NULL)
		return NULL;

	int lhsLength = strlen(lhs);
	int rhsLength = strlen(rhs);
	char *result = new char[lhsLength * rhsLength + 1];
	for (int i = 0; i <= lhsLength * rhsLength; i++)
		result[i] = '0';
	int i = lhsLength - 1;
	int j = rhsLength - 1;
	int k = 0;
	int carry = 0;
	int round = 0;

	while (i >= 0)
	{
		k = round;
		j = rhsLength - 1;
		carry = 0;
		while (j >= 0)
		{
			int numLhs = lhs[i] - '0';
			int numRhs = rhs[j] - '0';
			int sourceNum = result[k] - '0';
			int mul = numLhs * numRhs + carry + sourceNum;

			carry = mul / 10;
			mul = mul % 10;
			result[k] = mul + '0';

			k++;
			j--;
		}

		int num = result[k] - '0' + carry;
		if (num >= 10)
		{
			result[k] = num % 10 + '0';
			result[++k] = '1';
		}
		else
		{
			result[k] = num + '0';
		}

		round++;
		i--;
	}

	result[++k] = 0;
	reverse(result, result + k);

	return result;
}

void main()
{
	const char *lhs = "87695";
	const char *rhs = "898";

	char *result = multiply(lhs, rhs);
	if (result != NULL)
		cout << "sum = " << result << endl;
	cout << 87695 * 898 << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值