学习记录——高精度加法和乘法

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

const int maxn = 1000;
int A[maxn], B[maxn], C[maxn];

int main()
{
	string a, b;
	cin >> a >> b;
	int len = max(a.size(), b.size());//结果的位数

	//反向保存
	for (int i = a.length() - 1; i >= 0; --i)
		A[a.length()-i] = a[i] - '0';
	for (int i = b.length() - 1; i >= 0; --i)
		B[b.length()-i] = b[i] - '0';

	//相加
	for (int i = 1; i <= len; ++i)
	{
		C[i] += A[i] + B[i];
		//处理进位
		C[i + 1] = C[i] / 10;
		C[i] %= 10;
	}

	if (C[len+1])//进位了则长度加1
		len++;
	for (int i = len ; i >= 1; --i)//反向输出
		cout << C[i];

	return 0;
}
#include <iostream>
using namespace std;

const int maxn =10000;
int a[maxn], b[maxn], c[maxn];

int main()
{
	string x, y;
	cin >> x >> y;
	int lx = x.length();
	int ly = y.length();

	//反向保存
	for (int i = lx - 1; i >= 0; --i)
		a[lx - i] = x[i] - '0';
	for (int i = ly - 1; i >= 0; --i)
		b[ly - i] = y[i] - '0';

	//计算贡献--a[i]*b[j]的结果在第i+j-1位上
	for (int i = 1; i <= lx; ++i)
		for (int j = 1; j <= ly; ++j)
			c[i + j - 1] += a[i] * b[j];

	int len = lx + ly;//乘积的位数不超过两数位数之和

	//处理进位
	for (int i = 1; i <= len; ++i)
	{
		c[i + 1] += c[i] / 10;
		c[i] %= 10;
	}

	//去掉前导0
	while (!c[len])
		len--;

	//输出
	for (int i = max(1,len); i >= 1; --i)
		cout << c[i];

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值