Java中 BigInteger 的常用方法与注意事项

有时处理数字范围较大的数字相对麻烦,但有了BigInteger就可以完美解决,BigInteger具体的范围到底有多大,我之前查找了下,说是理论无穷大,看内存的大小(只供参考)

 

 

本文主摘:

  • int 与 BigInteger之间的相互转化方法
  • 使用BigInteger时的注意事项
  • BigInteger的常用方法

 

主摘1:

 1 import java.math.*;
 2 public class Day1{
 3     public static void main(String[] args){    
 4         //int 与 BigInteger之间的正确转换方法:        
 5         //int 转换为 BigInteger的方法:
 6         int p = 1;
 7         BigInteger a = BigInteger.valueOf(p);
 8         
 9         
10         //BigInteger 转换为 int的方法:
11         BigInteger d = new BigInteger("9");
12         int temp = d.intValue();*/
13     }
14 }



主摘2:

注意
  1:下边这种格式是错误的,错误的,错误的!别看错,是错误的!BigInteger 与 int 之间是不能直接相互转化的,别直接用
1 import java.math.*;
2 public class Day1{
3     public static void main(String[] args){    
4         BigInteger temp = new BigInteger("9");
5         int a = 1;
6         System.out.println(temp+a);
7     }
8 }

  2:使用BigInteger时要引用:import java.math.*;

 

 

主摘3:

 1 import java.math.*;
 2 public class Day1{
 3     public static void main(String[] args){    
 4         //常用方法:        
 5         BigInteger temp = new BigInteger("9");
 6         BigInteger temp1 = new BigInteger("6");
 7         BigInteger temp2 = new BigInteger("-6");
 8         //add();-------加法
 9         System.out.println(temp.add(temp1));        
10         //subtract();-------减法
11         System.out.println(temp.subtract(temp1));    
12         //multiply()-------乘法
13         System.out.println(temp.multiply(temp1));    
14         //divide()-------相除取整
15         System.out.println(temp.divide(temp1));
16         //remainder()与mod()-------取余
17         System.out.println(temp.remainder(temp1));
18         System.out.println(temp.mod(temp1));
19         //negate()------取相反数
20         System.out.println(temp.negate());
21         //abs()------取绝对值
22         System.out.println(temp2.abs());
23         //min(),max()------取最大与最小值
24         System.out.println(temp1.min(temp2));
25         System.out.println(temp1.max(temp2));
26         //gcd()------取最大公约数
27         System.out.println(temp1.gcd(temp));
28     }
29 }

如有个别回答错误,评论指出,我必更改,谢谢!😝

posted @ 2019-02-07 16:32  高欣的博客  阅读(3490)  评论(0编辑  收藏  举报