本文系fcbruce个人原创整理,转载请注明出处http://blog.csdn.net/u012965890/article/details/40432511,谢谢!
我们知道在C/C++中int型可处理-2^31~2^31-1(32位及以上编译器),long long型可处理-2^63~2^63-1的数据,这实际上是非常有限的,在很多情况下,我们往往会处理范围更大的数据。Java中有BigInteger类,python中想要多大就有多大(取决于内存),但是C/C++就显得有些乏力,这时候我们会手写大数类,用一个数组记录一个数,来模拟竖式计算。通常我们会一位一位地储存数据,这样易于实现,逻辑清晰,方便理解,但是一定程度上牺牲了效率,浪费了资源,那么能否多位存储数据并操作呢,显然是可以的。
我们知道int类型能表示的最大数量级为10^9左右,为了避免乘法溢出,我们不妨用一个int存储4位数字(10^4),可以轻易写下如下代码(仅含加、减、乘和比较操作):
/*
*
* Author : fcbruce <fcbruce8964@gmail.com>
*
* Time : Fri 24 Oct 2014 02:43:41 PM CST
*
*/
#include <cstdio>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <ctime>
#include <cctype>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <set>
#define sqr(x) ((x)*(x))
#define LL long long
#define itn int
#define INF 0x3f3f3f3f
#define PI 3.1415926535897932384626
#define eps 1e-10
#ifdef _WIN32
#define lld "%I64d"
#else
#define lld "%lld"
#endif
#define maxm
#define maxn
using namespace std;
const int maxl = 233;
struct bign
{
static int width;
static int mod;
int len,s[maxl];
bign()
{
memset(s,0,sizeof s);
len=1;
}
bign(int num)
{
*this=num;
}
bign(long long num)
{
*this=num;
}
bign(const char *s)
{
*this=s;
}
bign operator = (int num)
{
char s[maxl];
sprintf(s,"%d",num);
*this=s;
return *this;
}
bign operator = (long long num)
{
char s[maxl];
sprintf(s,lld,num);
*this=s;
return *this;
}
bign operator = (const char *s)
{
int l=strlen(s);
len=0;
for (int i=l-1;i>=0;i-=width,len++)
{
(*this).s[len]=0;
for (int j=max(0,i-width+1);j<=i;j++)
(*this).s[len]=(*this).s[len]*10+s[j]-'0'