keep it simple, stupid

导航

大数相乘

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

posted on 2011-09-15 17:17  tujiaw  阅读(167)  评论(0)    收藏  举报