加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

【大数】递归写大数感觉良好

发布时间:2020-12-14 03:55:13 所属栏目:大数据 来源:网络整理
导读:上软件工程课讲到迭代开发突然想到了用递归写大数怎么样(效率和节操是一个价)。 ? 于是写了个加法的,感觉良好..... ? #include iostream#include stringusing namespace std;class Adder{private:string a;string b;string c;int alen;int blen;void work

上软件工程课讲到迭代开发突然想到了用递归写大数怎么样(效率和节操是一个价)。

?

于是写了个加法的,感觉良好.....

?

#include <iostream>
#include <string>

using namespace std;

class Adder{

private:
	string a;
	string b;
	string c;
	
	int alen;
	int blen;
	
	void work(int add=0);
	
public:
	Adder(string& x,string& y);
 	friend ostream& operator << (ostream &o,Adder& a);	
};

Adder::Adder(string& x,string& y):a(x),b(y),c(""),alen(x.length()),blen(y.length()){this->work();}

void Adder::work(int add){
	
	if(alen) add += a[alen-1] - '0',alen--;
	if(blen) add += b[blen-1] - '0',blen--;
	
	if(alen||blen||add) c.push_back(char(add%10 + '0')),work(add/10); 
}

ostream& operator << (ostream& o,Adder& ad){
	
	int len = ad.c.length();
		
	for(;len--;) o << ad.c[len];
	
	return o;
}

int main(){
	
	string a = "123";
	string b = "789"; 
	
	Adder ans(a,b);
	
	cout << ans << endl; 
	
	return 0;
}


?

补上大数乘法的,这个写水了......

?

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

class Multer{
	
private:
	string a;
	string b;
	string c;
	int alen;
	int blen;
	
	void work(int loc=0);	
	int toInt(char x);
	
public:
	Multer(string& x,string& b);	
	string ans();
	friend ostream& operator << (ostream& o,Multer& m);		
}; 

Multer::Multer(string& x,string& y){

	a = x;
	b = y;

	c = "";
	
	alen = x.length();
	blen = y.length();
	
	this->work();
}

int Multer::toInt(char x){return x - '0';}

void Multer::work(int loc){
	
	if(!blen) return;

	for(int i=1;i<=alen;++i){
				
		int add = c[i+loc-1] + toInt(a[alen-i]) * toInt(b[blen-1]);
		
		if(c.length() <= i+loc-1) c.push_back(add%10);
		
		else c[i+loc-1] = add%10;
				
		if(add/10 && c.length() <= i+loc)   c.push_back(add/10);	
		
		else c[i+loc] += add/10;
	}
	
	blen--,work(loc+1);
}

string Multer::ans(){return c;}

ostream& operator << (ostream& o,Multer& m){
	
	int len = m.c.length();
	
	for(;len--;) o << (int)m.c[len];
	
	return o;
}

int main(){
	
	return 0;
}


强迫症吐槽:C++类里的格式究竟怎么样才行啊...

?

A:

class Show{
	
public:
	//
	//
	//
	
private:		
	//
	//
	//
};


?

B:

class Show{
	
	public:
	
		//
		//
		//
		
	private:	
		
		//
		//
		//
};


C:

class Show{
	
	public:		//
			    //
			    //
		
	private:	//
			    //
			    //
};

最早我是C型的,但是用QT给我用回A类型了.....

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读