c++ 大数模板 及例题

2014-11-24 09:20:50 · 作者: · 浏览: 0

比较好的一个大数模板 贴在这里备用

string sum(string s1,string s2)
{
	if(s1.length()
  
   =0;i--,j--)
	{
		s1[i]=char(s1[i]+(j>=0 s2[j]-'0':0));   //注意细节
		if(s1[i]-'0'>=10)
		{
			s1[i]=char((s1[i]-'0')%10+'0');
			if(i) s1[i-1]++;
			else s1='1'+s1;
		}
	}
	return s1;
}
  

顺便在来个例题,用大数模板求大斐波那契数 nyoj655光棍的yy

直接套用模板没有任何技巧代码:

#include 
  
   
#include 
   
     #include 
    
      using namespace std; string sum(string s1,string s2) { if(s1.length()
     
      =0;i--,j--) { s1[i]=char(s1[i]+(j>=0 s2[j]-'0':0)); //注意细节 if(s1[i]-'0'>=10) { s1[i]=char((s1[i]-'0')%10+'0'); if(i) s1[i-1]++; else s1='1'+s1; } } return s1; } int main() { int n,T; scanf(%d,&T); while(T--) { string s;cin>>s; if(s.size()==1){ printf(1 );continue; } else if(s.size()==2) { printf(2 );continue; } string ans,a=1,b=2; for(int i=3;i<=s.size();i++) { ans=sum(a,b); a=b; b=ans; } cout<