大数类

大数类

#include <iostream>
#include <cstdio>
#include <cstring> 

using namespace std;

const int maxn = 1000;

struct Bign{
	
	int len;  //有效长度 
	int s[maxn]; //存放大数
	
	//构造函数 ,变量初始化 
	Bign(){ memset(s,0,sizeof(s));len = 1;} 
	
	//重载赋值操作,可以直接用 x = "123456789034" 的方式来为x赋值  
	//将字符串逆序存储在 int s[]内 
	Bign operator = (const char * num){
		len = strlen(num);
		for(int i=0;i<len; i++) s[i] = num[len-i-1] - '0';
		return *this;
	}
	
	Bign operator = (int num){
		char s[maxn];
		sprintf(s, "%d", num);
		*this = s;
		return *this;
	}
	
	Bign(int num){ *this = num; }
	Bign(const char* num){ *this = num; }
	
	string toString() const{
		string str = "";
		for(int i=len-1; i>=0; i--) str += (char)(s[i]+'0');
		return str;
	}
	
	Bign operator + (const Bign &b ) const {
		Bign c; c.len = 0;
		int i,carry,maxl = max(len,b.len);
		for( i =carry =0; i<maxl; i++){
			int tmp = s[i] + b.s[i] + carry;
			c.s[c.len++] = tmp % 10;
			carry = tmp / 10;
		}
		while(i<len)  c.s[c.len++] += s[i++];  
		while(i<b.len)  c.s[c.len++] += b.s[i++]; 
		return c;
	} 
	
	//去除数组中多余的0 
	void clear() {
		while(len>1 && !s[len-1])len--; 
	} 
	
	Bign operator * (const Bign &b) const {
		Bign c; c.len = len + b.len;
		//对于a的每一位 用 b的每一位去成一遍 
		for(int i=0; i<len; i++) 
			for(int j=0; j<b.len; j++)
				c.s[i+j] += s[i] * b.s[j];
		//处理进位 
		for(int i=0; i<c.len-1; i++){
			c.s[i+1] += c.s[i] / 10;
			c.s[i] %= 10;
		}
		//去除多余0,更正c.len 
		c.clear();
		return c;		
	}
	
	friend istream &operator >> (istream &in, Bign &n) {
		string s;
		in >> s;
		n = s.c_str();
		return in;
	} 
	
	friend ostream &operator << (ostream &out, const Bign &n) {
		out << n.toString();
		return out;
	}
		
};


int main ()
{
	
	Bign n1;
	n1 = "23784589493050034059009342324324";
	cout << " n1 = " << n1 << endl; // n1 = 23784589493050034059009342324324
	
	Bign n2; 
	n2 = 1234567890;
	cout << " n2 = " << n2 << endl; // n2 = 1234567890
	
	Bign n3("9787827383654329"); 
	cout << " n3 = " << n3 << endl; // n3 = 9787827383654329
	
	Bign n4(827383654); 
	cout << " n4 = " << n4 << endl; // n3 = 827383654
	
	Bign n5 = "78398249420049293949589999999";
	Bign n6 = "1344234769898495120000001"; 
	cout << " n5 + n6 = " << (n5+n6) << endl; // n5 + n6 = 78399593654819192444710000000

	Bign n7 = "7293949589999999";
	Bign n8 = "14769896431116"; 
	cout << " n7 * n8 = " << (n7*n8) << endl; // n7 * n8 = 107730880018080996672543568884
											
	 
}