最简单的思路是直接用int型数组存储大数的每一位,程序比较容易实现,但是效率稍低,直接上代码。
#include<iostream>
#include<cstring>
using namespace std;
class bign
{
int num[1000];
int pos_high;//最高位所在位置
public:
bign() { pos_high = -1; }
bign(const bign&t)
{
memcpy(num, t.num, sizeof(num));
pos_high = t.pos_high;
}
bign operator=(const bign&t)
{
memcpy(num, t.num, sizeof(num));
pos_high = t.pos_high;
return t;
}
bign operator=(const char*t)
{
int len = strlen(t);
for (int i = 0;i < len;i++)
num[i] = t[len - i - 1]-'0';
pos_high = len - 1;
return *this;
}
bign operator+(const bign&t)const
{
bign ans;
int i,r = 0,s;
for ( i = 0;i <= pos_high || i <= t.pos_high;i++)
{
if (i > t.pos_high)
{
s = num[i] + r;
ans.num[i] = s%10;
r = s / 10;
}
else if (i > pos_high)
{
s = t.num[i] + r;
ans.num[i] = s % 10;
r = s / 10;
}
else
{
s = num[i] + t.num[i]+r;
ans.num[i]=s % 10;
r = s / 10;
}
}
if (r > 0)
ans.num[i] = 1, ans.pos_high = i;
else
ans.pos_high = i - 1;
return ans;
}
bign operator*(const bign&t)const
{
bign te,ans;
int i, j,r,s;
char str[1000];
for (i = 0;i <= t.pos_high;i++)
{
r = 0;
te.pos_high = 0;
for