java-BigInteger 从入门到入坑 完整版

本文详细介绍了Java中的BigInteger类,包括其数据范围、输入方法、构造方法、基本运算、比较大小、常量、类型转换以及二进制运算的实际应用。通过实例解析了如何处理大整数的阶乘问题,并提供了LeetCode 1808题目的解决方案。
摘要由CSDN通过智能技术生成

BigInteger 的数据范围远大于int,long。用于应对大的数据。

输入方法

nextBigInteger():控制台读入一个BigInteger型数据,类似于int型的nextInt();

//读入方法:nextBigInteger()
	@Test
	public void test5() {
   
		Scanner scan = new Scanner(System.in);				// 读入
		int n = scan.nextInt(); 							// 读入一个int;
		BigInteger m = scan.nextBigInteger();				// 读入一个BigInteger;
		while(scan.hasNext()){
   	
			System.out.print("scan.hasNext()=" + scan.hasNext());
		}
	}

构造方法

默认为十进制,也是我们最常用的,同时也支持自定义进制类型(已存在的);

//进制转换
@Test
public void testScale() {
   
	//在构造将函数时,把radix进制的字符串转化为BigInteger
	String str = "1011100111";
	int radix = 2;
	BigInteger interNum1 = new BigInteger(str,radix);	//743

	//我们通常不写,则是默认成10进制转换,如下:
	BigInteger interNum2 = new BigInteger(str);			//1011100111
	BigInteger ans=BigInteger.valueOf(1232);
}

基本运算

返回值为BigInteger类型:add(),subtract(),multiply(),divide(),mod(),remainder(),pow(),abs(),negate();

//基本运算:add(),subtract(),multiply(),divide(),mod(),remainder(),pow(),abs(),negate()
@Test
public void testBasic() {
   
	BigInteger a = new BigInteger("13");
	BigInteger b = new BigInteger("4");
	int n = 3;

	//1.加
	BigInteger bigNum1 = a.add(b);			//17
	//2.减
	BigInteger bigNum2 = a.subtract(b);		//9
	//3.乘
	BigInteger bigNum3 = a.multiply(b);		//52
	//4.除
	BigInteger bigNum4 = a.divide(b);		
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值