要点:
- 加法直接传递进位,乘法先保留进位,后统一处理
- 使用int数组存储,空间浪费,处理方便
- 建立bigNum结构(或类),处理清晰方便
代码:
基础定义
#include<bits/stdc++.h>
using namespace std;
char num1[10000];
char num2[10000];
struct bigNum
{
int num[1000] = {};
int len;
};
void scan(char* a,bigNum* b)
{
int l = strlen(a);
b->len = l;
for (int i = 0; i < l; i++)
{
b->num[i] = a[l - i - 1]-'0';
//cout << b->num[i];
}
}
加法
bigNum bigAdd(bigNum* a, bigNum* b)
{
int carry = 0; int i = 0; int temp = 0;
int l1 = a->len; int l2 = b->len;
bigNum res;
while (i < l1 || i < l2)
{
temp = a->num[i] + b->num[i] + carry;
//cout << temp << endl;
res.num[i] = temp % 10;
carry = temp / 10;
//cout << "c:" << carry << endl;
i++;
}
res.num[i] = carry;
if (res.num[i] == 0)
res.len = i+1;
else
res.len = i ;
return res;
}
乘法
bigNum bigMul(bigNum* a, bigNum* b)
{
bigNum res;
for (int i = 0; i < a->len; i++)
for (int j = 0; j < b->len; j++)
res.num[i + j] += a->num[i] * b->num[j];
int i = 0;
while (res.num[i] != 0)
{
if (res.num[i] > 9)
{
res.num[i + 1] += res.num[i] / 10;
res.num[i] = res.num[i] % 10;
}
i++;
}
res.len = i;
return res;
}
测试主函数
int main()
{
bigNum a, b;
cin >> num1 >> num2;
scan(num1, &a);
scan(num2, &b);
bigNum c=bigMul(&a, &b);
if (c.len == 0)
cout << 0;
else
{
for (int i = c.len-1; i >= 0; i--)
cout << c.num[i];
}
return 0;
}
标签:bigNum,cout,大数,int,res,len,num,加法,乘法
From: https://www.cnblogs.com/Arc-ux/p/18362915