Java 处理超大数类型之BigInteger案例详解

作者:温柔的谢世杰 时间:2021-06-20 15:36:38 

一、BigInteger介绍

如果在操作的时候一个整型数据已经超过了整数的最大类型长度 long 的话,则此数据就无法装入,所以,此时要使用 BigInteger 类进行操作。这些大数都会以字符串的形式传入。

BigInteger 相比 Integer 的确可以用 big 来形容。它是用于科学计算,Integer 只能容纳一个 int,所以,最大值也就是 2 的 31 次访减去 1,十进制为 2147483647。但是,如果需要计算更大的数,31 位显然是不够用的,那么,此时 BigInteger 就能满足我们的需求了。

BigInteger 能够容纳的位数那可就大了,我简单试了一下,上千位没有任何问题。除了容量大之外,BigInteger 还封装了一些常见的操作,比如 ±*/ 的基本操作,还有绝对值,相反数,最大公约数,是否是质数等等的运算。

二、BigInteger常见函数

  • BigInteger(String value):构造方法,

  • BigInteger add(BigInteger value):加法,

  • BigInteger subtract(BigInteger value):减法,

  • BigInteger multiply(BigInteger value):乘法,

  • BigInteger divide(BigInteger divisor):除法,

  • BigInteger modInverse(BigInteger m):求模,

  • BigInteger pow(int exponent):乘方,

  • BigInteger max(BigInteger value):最大数,

  • BigInteger min(BigInteger value):最小数,

  • BigInteger abs():绝对值,

  • BigInteger negate():相反数,

  • int intValue():转化int,将BigInteger类型数据转为int。

  • BigInteger valueOf(long val):转为BigInteger,将long类型转为BigIntege类型

示例代码

【题目】

输入一个整数 n 1<n<10^9
输出一个整数
找出其所有非空子集中所有元素个数之和,然后对 10^9+7 取模,输出结果
例如输入 2,有 {1},{2},{1,2} 3 个非空子集,所有元素个数之和为 4
输出结果为 4

思路

用 int 肯定会超,需要用到 BigInteger
对于输入 n,求得所有元素之和为 n*2^(n-1)
然后再对 10^7+7 取模即可


import java.math.BigInteger;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
       Scanner sc = new Scanner(System.in);
       String n = sc.next();
       BigInteger res = count(new BigInteger(n));
       BigInteger m = BigInteger.valueOf(10).pow(7).add(BigInteger.valueOf(7));
       System.out.println(res.mod(m));;
   }

// 计算公式 n*2^(n-1)
   static BigInteger count(BigInteger n) {
       return n.multiply(BigInteger.valueOf(2).pow(n.intValue()-1));
   }
}

来源:https://blog.csdn.net/qq_33945246/article/details/105202522

标签:java,BigInteger
0
投稿

猜你喜欢

  • RocketMQ源码解析broker 启动流程

    2022-12-25 10:50:54
  • Java并发编程面试之线程池

    2023-11-11 10:58:33
  • Android 显示GIF图片实例详解

    2023-08-06 09:11:52
  • Android布局之帧布局FrameLayout详解

    2023-08-07 04:45:29
  • AQS加锁机制Synchronized相似点详解

    2023-08-04 22:36:55
  • java实现单链表、双向链表

    2023-02-09 03:15:59
  • opencv3/C++图像滤波实现方式

    2023-06-23 15:37:08
  • Java值传递之swap()方法不能交换的解决

    2023-11-12 20:54:50
  • java 实现发短信功能---腾讯云短信

    2023-11-29 11:03:49
  • 解决Android软键盘弹出覆盖h5页面输入框问题

    2023-06-19 11:33:24
  • Spring之spring-context-indexer依赖详解

    2023-11-23 12:21:41
  • Java经典面试题最全汇总208道(四)

    2023-11-08 23:59:26
  • Java中Validated、Valid 、Validator区别详解

    2023-11-11 13:53:31
  • Java 数组高频考点分析讲解

    2021-09-01 13:14:36
  • 详述IntelliJ IDEA插件的安装及使用方法(图解)

    2023-11-26 04:45:06
  • MyBatis映射文件resultMap元素中使用多个association的方法

    2023-11-29 06:53:51
  • jQuery 动画效果代码分享

    2023-11-24 00:10:12
  • 重写hashCode()和equals()方法详细介绍

    2023-11-24 16:13:33
  • 线程局部变量的实现 ThreadLocal使用及场景介绍

    2023-11-10 03:19:26
  • Java中ReentrantLock4种常见的坑

    2021-09-26 10:51:46
  • asp之家 软件编程 m.aspxhome.com