大数相乘

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

C++的通过了较复杂的测试:

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值