C++大数相乘(模拟)

题意:

给出两个特别大的数,求两数相乘结果。

数长度为200位,数最大可能到达10的200次方

#include <bits/stdc++.h>
using namespace std;
string multiply(string num1, string num2) {
	if(num1 == "0" || num2 == "0"){      // 如果有0,直接返回
		return "0";
	}
	string ans = "";
	int a[550];
	memset(a, 0, sizeof(a));
	int u = 0;
	int len1 = num1.size(), len2 = num2.size();
	for(int i = len1 - 1; i >= 0; i--){       //两个for循环模拟乘法
		for(int j = len2 - 1, k = u; j >= 0; j--, k++){
			a[k] += (num1[i] - '0') * (num2[j] - '0');
		}
		u++;
	}
	int len = len1 + len2;     // 最终结果的长度最大为len1+len2
	for(int i = 0; i < len; i++){
		if(a[i] >= 10){
			a[i+1] += a[i] / 10;     // 往前进位
			a[i] = a[i] % 10;        // 保留个位
		} 
	}
	while(a[len-1] == 0){     // 前导为0
		len--;
	}
	for(int i = len-1; i >= 0; i--){
		ans += a[i]+'0';      // 反向为结果
	}
	return ans;
}
int main(){
	string s1, s2;
	cin >> s1 >> s2;
	string s = multiply(s1, s2);
	cout << s << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值