【题】大数乘法

基本原理:将两个数字转换成字符,放到字符数组中。为了防止溢出。

思路:

        在计算十进制数 123 * 45 时,首先计算 123 * 5 = 615,然后计算 123 * 4 = 492,最终结果是 615 + 492 * 10 = 5535。

  大数乘法的计算过程与此相同:对于A(a0a1a2...an-1) * B(b0b1b2...bm-1),并假设N≥M(被乘数位数不小于乘数时,效率最高),对于B中的每一位 bi,计算其与A的乘积,并在后面补上 i 个零,将结果累加,即为A与B的乘积。

 

 

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main()
{
	string num1,num2;
	cin>>num1;
	cin>>num2;
	const char * n1;
	const char *n2;
	if(num1.size() < num2.size())
	{
		n1 = num2.c_str();
		n2 = num1.c_str();
	}
	else 
	{
		n1 = num1.c_str();
		n2 = num2.c_str();
	}
	char* n = new char [strlen(n1)+strlen(n2)+1];
	for(int i =0; i<strlen(n1)+strlen(n2);i++)
	{
		n[i] = '0';
	}
	n[strlen(n1)+strlen(n2)] = '\0';
	int count = 0,flag = 0;
	for(int i = strlen(n1)-1;i>=0;i--)
	{
		flag++;
		int x1 = n1[i]-'0';
		char carry = '0';
		for(int j = strlen(n2)-1;j>=0;j--)
		{
			int x2 = n2[j]-'0';
			int sum = x1*x2 + (carry-'0') + n[count] - '0';
			n[count++]=(sum%10)+'0';
			carry =(sum/10) + '0';

		}
		if(carry != '0')
		{
			n[count] = carry;
			count=flag;
		}
		else
			count = flag;
	}
	for(int i = strlen(n)-1;i>=0;i--)
	{
		if((i==strlen(n)-1)&&(n[i]=='0'))
		{
			continue;
		}
		cout<<n[i];
	}
	cout<<endl;
	delete[]n;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值