Skip to content

C++大数相乘

Published: at 12:06 PM | 2 min read

#include <stdio.h>
#include <assert.h>

void BigNumMultiply(const char *str1, const char *str2, char *product)
{
	assert(str1 != NULL && str2 != NULL && product != NULL);

	int i, j;
	int len1 = (int)strlen(str1);
	int len2 = (int)strlen(str2);
	int *dest = (int*)malloc(sizeof(int)*(len1+len2+1));
	
	for (i=0; i<len1+len2+1; i++) { dest[i] = 0; }

	for (i=0; i<len1; i++)
	{
		for (j=0; j<len2; j++)
		{
			dest[i+j+1] += (str1[i]-'0')*(str2[j]-'0');
		}
	}

	for (i=len1+len2-1; i>=0; i--)
	{
		// 当i=0时dest[0]=0,这个条件不成立,所以不用担心dest[-1]
		if (dest[i] >= 10)
		{
			dest[i-1] += dest[i]/10;
			dest[i] %= 10;
		}
		product[i] = dest[i]+'0';
	}

	if (product[0] == '0')
	{
		i = 1;
		while (product[i] != '\0')
		{
			product[i-1] = product[i];
			i++;
		}
		product[i-1] = '\0';
	}

	free(dest);
	return;
}

int main(void)
{
	char product[50] = {0};

	BigNumMultiply("234324", "54651", product);
	printf("%s\n", product);

	getchar();
	return 0;
}

测试:


    string multiply(string num1, string num2) {
		std::string result;
		std::vector<int> data;
		int total = num1.size() + num2.size() + 1;
		data.resize(total, 0);
		for (std::size_t i=0; i<num1.size(); i++) {
			for (std::size_t j=0; j<num2.size(); j++) {
				data[i+j+1] += (num1[i]-'0') * (num2[j]-'0');
			}
		}
		for (int i=num1.size()+num2.size()-1; i>=0; i--) {
			if (data[i] >= 10) {
				data[i-1] += data[i] / 10;
				data[i] %= 10;
			}
			result.insert(result.begin(), data[i] + '0');
		}
		while (result.size() > 1 && result[0] == '0') {
			result = result.erase(0, 1);
		}
		return result;
    }