偶尔会遇到大数的题,首选Java,有的题目C++的char数组模拟也可以(从第一位开始遍历,逢十进一即可)

大整数 BigInteger

HDUOJ 1002 A + B Problem II(大数加法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.*;
import java.math.*;

public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner (System.in);

int i,n=in.nextInt();

BigInteger a,b,c;

for(i=1; i<=n; i++){
if(i!=1)
System.out.println("");
a=in.nextBigInteger();
b=in.nextBigInteger();

c=a.add(b);
System.out.println("Case "+i+":");
System.out.println(a+" + "+b+" = "+c);
}
}
}

这个题是最简单的Java大数了

其次是HDUOJ 1042 N!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.io.*;
import java.math.*;
import java.util.*;
import java.text.*;

public class Main
{
public static void main(String args[])
{
// Scanner in = new Scanner(System.in);
Scanner in = new Scanner (new BufferedInputStream(System.in));
while (in.hasNextInt()){
int i,n = in.nextInt();
// BigInteger sum = BigInteger.valueOf(1);
BigInteger sum = new BigInteger("1");
for(i = 2; i <= n ; i++) {
BigInteger z = BigInteger.valueOf(i);
sum = sum.multiply(z);
}
System.out.println(sum);
}
}
}

BigInteger和BigDecmial两个类理论上可以求超级大超级大的一个数,最大值取决于你电脑内存!
BigInter 可以看作是一种数据类型

声明:

BigInteger a;

赋值有2种方式
第一种:

a = new BigInteger("123");
//"123"是一个字符串,将字符串转化成一个数字

第二种:

a = BigInteger.valueOf(i); 
//这里的i就是一个数,可以用于for循环

加减乘除四个方法:

a = a.add(BigInteger other);//加
a = a.multiply(BigInteger other);//乘
a = a.subtract(BigInteger other);//减
a = a.divide(BigInteger other);//除

大浮点数 BigDecimal

HDU 1753 大明A+B

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.io.*;
import java.math.*;
import java.util.*;
import java.text.*;

public class Main{
public static void main(String args[]) {
Scanner in = new Scanner (new BufferedInputStream(System.in));
BigDecimal a , b;
while(in.hasNextBigDecimal()) {
a = in.nextBigDecimal();
b = in.nextBigDecimal();
System.out.println(a.add(b).stripTrailingZeros().toPlainString());
}
}
}

顺带一提, 开数组:

BigInteger a[] = new BigInteger[100];