处理大数有两种方法,用C++自己手动模拟,和用JAVA里面的大数类,这两种要灵活掌握。
例题1:大数加法(hdu 1002)
#include <iostream>#include <cmath>#include <iomanip>#include <fstream>#include <stdio.h>#include <string>using namespace std;const int maxn=1000;int max(int a,int b){ if(a>b) return a; else return b;}class bign{ public: int len; int s[maxn];};bign addbignum(bign a,bign b){ bign c; c.len=0; for(int i=0,g=0;g||i<max(a.len,b.len);i++) { int x=g; if(i<a.len) x+=a.s[i]; if(i<b.len) x+=b.s[i]; c.s[c.len++]=x%10; g=x/10; } return c;}int main(){ int testcase; cin>>testcase; for(int z=1;z<=testcase;z++) { string tmpa,tmpb; bign a,b,c; cin>>tmpa>>tmpb; a.len=tmpa.size(); b.len=tmpb.size(); for(int i=0;i<a.len;i++) { a.s[i]=tmpa[a.len-i-1]-'0'; } for(int j=0;j<b.len;j++) { b.s[j]=tmpb[b.len-j-1]-'0'; } c=addbignum(a,b); cout<<"Case "<<z<<":"<<endl; cout<<tmpa<<" + "<<tmpb<<" = "; for(int p=c.len-1;p>=0;p--) { cout<<c.s[p]; } cout<<endl; if(z!=testcase) cout<<endl; } return 0;}
例题2:大数乘方(POJ 1001),这里用JAVA再练习一下。。注意toPlainString的作用(不出现科学计数,形如ios::fixed),和striptrailingZeros的作用(忽略后面的结尾0)
import java.io.BufferedInputStream;import java.math.BigDecimal;import java.util.Scanner;public class Main {public static void main(String args[]){ Scanner cin=new Scanner(new BufferedInputStream(System.in)); BigDecimal a; int b; while(cin.hasNext()) { BigDecimal c; a=cin.nextBigDecimal(); b=cin.nextInt();//直接调用 c=a.pow(b).stripTrailingZeros(); System.out.println(c.toPlainString().replaceAll("^0", "")); }}}