大整数问题

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;
}


你可能感兴趣的:(大整数问题)