【问题标题】:How to assign a very large number to BigInteger?如何为 BigInteger 分配一个非常大的数字?
【发布时间】:2015-06-20 17:09:12
【问题描述】:

给定以下输入:

4534534534564657652349234230947234723947234234823048230957349573209483057
12324000123123

我已尝试通过以下方式将这些值分配给BigInteger

public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        BigInteger num1 = BigInteger.valueOf(sc.nextLong());
        sc.nextLine();
        BigInteger num2 = BigInteger.valueOf(sc.nextLong());

        BigInteger additionTotal = num1.add(num2);
        BigInteger multiplyTotal = num1.multiply(num2);

        System.out.println(additionTotal);
        System.out.println(multiplyTotal);
    }

第一个值超出了 Long 数字的边界,因此出现以下异常:

线程“主”java.util.InputMismatchException 中的异常:对于输入 细绳: “4534534534564657652349234230947234723947234234823048230957349573209483057”

我假设 BigInteger 期望 Long 类型与 valueOf() 方法一起使用(如 here 所述)。如何将极大的数字传递给 BigInteger?

【问题讨论】:

    标签: java biginteger value-of


    【解决方案1】:

    当输入的数字不适合longuse the constructor that takes a String argument

    String numStr = "453453453456465765234923423094723472394723423482304823095734957320948305712324000123123";
    BigInteger num = new BigInteger(numStr);
    

    【讨论】:

      【解决方案2】:

      以字符串的形式读取巨大的数字。

      public static void main(String[] args)
      {
          Scanner in = new Scanner(System.in);
          String s = in.nextLine();
          BigInteger num1 = new BigInteger(s);
      
          s = in.nextLine();
          BigInteger num2 = new BigInteger(s);
      
          //do stuff with num1 and num2 here
      }
      

      【讨论】:

        【解决方案3】:

        【讨论】:

          【解决方案4】:

          使用字符串构造函数。

          像这样。

          http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger(java.lang.String)

          如果 long 数据类型可以处理任意大的数字,则不需要 BigInteger。

          【讨论】:

            猜你喜欢
            • 2022-08-15
            • 2013-10-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-09-19
            • 1970-01-01
            相关资源
            最近更新 更多