Sum of large numbers in java

65 Views Asked by At
import java.util.Scanner;
import java.math.BigInteger;

public class LargeSum {

    public static void main(String[] args) {
        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());  //runtime error
        BigInteger sum=new BigInteger(String.valueOf(arr[0]));
        for (int i=1; i<limit;i++) 
            sum=sum.add(arr[i]);
    }

}

I've written a code to find the sum of user given amount of large numbers in java using BigInteger class, but I reached a runtime error "java.lang.NumberFormatException: Zero length BigInteger". How can I fix this issue? Sample input:
5
37107287533902102798797998220837590246510135740250 46376937677490009712648124896970078050417018260538 74324986199524741059474233309513058123726617309629 91942213363574161572522430563301811072406154908250 23067588207539346171171980310421047513778063246676

1

There are 1 best solutions below

0
Reilas On

Advance to the next line first.

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

Or, use the Integer#parseInt method.

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

Output

5
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676

272819012982030361314614767301043585006837989465343