java中大数之和

问题描述 投票:0回答:1
    Scanner inp=new Scanner(System.in);
    int limit=inp.nextInt();
    BigInteger[] arr=new BigInteger[limit];
    for (int i=0; i<limit; i++) 
        arr[i]=new BigInteger(inp.nextLine());  
    BigInteger sum=new BigInteger(String.valueOf(arr[0]));
    for (int i=1; i<limit;i++) 
        sum=sum.add(arr[i]);

我已经编写了一段代码,使用 BigInteger 类在 java 中查找用户给定数量的大数的总和,但是我在第 5 行遇到了运行时错误“java.lang.NumberFormatException:零长度 BigInteger”。我该如何解决这个问题问题?

java biginteger
1个回答
0
投票

先前进到下一行。

int limit=inp.nextInt();
inp.nextLine();

或者,使用 Integer#parseInt 方法。

int limit=Integer.parseInt(inp.nextLine());

输出

5
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676

272819012982030361314614767301043585006837989465343
© www.soinside.com 2019 - 2024. All rights reserved.