今天参考课本写了一个关于二进制与十进制转换的程序,程序算法不难,但写完后测试发现不管是二转十仍是十转二,对于大于21亿即超过整数范围的数不能很好的转换。都会变成0.
参考书籍发现使用使用BigInteger能够解决这个问题。
因而查找了下JDK,而后测试几回终于写成功了!
使用心得以下:
1,BigInteger属于java.math.BigInteger,所以在每次使用前都要import 这个类。偶开始就忘记import了,因而总提示找不到提示符。
2,其构造方法有不少,但如今偶用到的有:html
BigInteger(String |
BigInteger(String |
如要将int型的2转换为BigInteger型,要写为BigInteger two=new BigInteger("2"); //注意2双引号不能省略
3,BigInteger类模拟了全部的int型数学操做,如add()==“+”,divide()==“-”等,但注意其内容进行数学运算时不能直接使用数学运算符进行运算,必须使用其内部方法。并且其操做数也必须为BigInteger型。
如:two.add(2)就是一种错误的操做,由于2没有变为BigInteger型。
4,当要把计算结果输出时应该使用.toString方法将其转换为10进制的字符串,详细说明以下:
java
String |
toString() 返回此 BigInteger 的十进制字符串表示形式。 |
输出方法:System.out.print(two.toString());
5,另外说明三个个用到的函数。 算法
BigInteger |
remainder(BigInteger |
BigInteger |
negate() 返回其值是 (-this) 的 BigInteger。 |
int |
compareTo(BigInteger |
remainder用来求余数。
negate将操做数变为相反数。
compare的详解以下:
api
public int compareTo(BigInteger val)
compareTo
in interface
Comparable<BigInteger>
val
- BigInteger to which this BigInteger is to be compared.
import java.math.BigInteger; public class BigIntegerDemo { public static void main(String[] args) { BigInteger big=BigInteger.ONE; System.out.println("BigInteger.ONE:"+big); System.out.println("nextProbablePrime:"+big.nextProbablePrime()); System.out.println("nextProbablePrime:"+big.nextProbablePrime()); big=BigInteger.TEN; System.out.println("BigInteger.TEN:"+big); big=BigInteger.ZERO; System.out.println("BigInteger.ZERO:"+big); } }
输出:less
BigInteger.ONE:1 nextProbablePrime:2 nextProbablePrime:2 BigInteger.TEN:10 BigInteger.ZERO:0