Java 大数使用

Java 大数BigInteger使用

由于在 Java中,在不使用大数的情况下,整数最大范围为long型(能够表示64位的整数),速度快 ,但是当运算超过long型的范围时,我们就需要用java.math.BigInteger(另外一个是java.math.BigDecimal,用于进行小数运算 )来表示任意大小的整数了,其内部用一个int[]数组来模拟一个非常大的整数

以下为BigInteger以及BigDecimal相关API介绍:
BigInteger相关API的使用
BigDecimal相关API的使用
以下用一个例子来实现BigInteger
**程序 :**将一个十六进制的字符串转换为十进制的字符串(支持输入多个字符串 )

未使用大数

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str ;
        int HEX = 16;
        while(sc.hasNext()){
            str = sc.nextLine();
            str = str.substring(2);
            int result = Integer.parseInt(str, HEX);
            System.out.println(result);
        }
    }
}

使用大数

import java.math.BigInteger;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str ;
        BigInteger HEX = new BigInteger("16");
        while(sc.hasNext()){
            str = sc.nextLine();
            str = str.substring(2);
            BigInteger result = new BigInteger("0");
            for(int i = 0; i < str.length(); i++){
                char ch = str.charAt(str.length()-1-i);
                if(ch >= 'A' && ch <= 'F'){
                    BigInteger tmp = HEX.pow(i).multiply(new BigInteger(Integer.toString((ch - 'A' + 10))));
                    result = result.add(tmp);
                }else{
                    BigInteger tmp = HEX.pow(i).multiply(new BigInteger(Character.toString(ch)));
                    result = result.add(tmp);
                }
            }
            System.out.println(result);
        }
    }
}

另外一种使用大数

import java.math.BigInteger;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str;
        int HEX = 16;
        while (sc.hasNext()) {
            str = sc.nextLine();
            str = str.substring(2);
        }
        System.out.println(new BigInteger(str, HEX));
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值