user7598275
user7598275

Reputation: 3

conversion of array of decimal string to biginteger

How can I convert array of string containing decimal numbers to big integer?

eg:

String s={"1","2","30","1234567846678943"};

My current code:

Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s[]= new String[n];

for(int i=0; i < n; i++){
 s[i] = in.next();
}

BigInteger[] b = new BigInteger[n];
for (int i = 0; i < n; i++) {
  b[i] = new BigInteger(String s(i));
}

Upvotes: 1

Views: 257

Answers (2)

Raman Sahasi
Raman Sahasi

Reputation: 31851

Just use new BigInteger(s[i]); instead of new BigInteger(String s(i));

FYI, you don't really have to use a separate String array to store initial values. You can directly store them in BigInteger array. Somewhat like this:

Scanner in = new Scanner(System.in);
int n = in.nextInt();

BigInteger[] b = new BigInteger[n];

for(int i=0; i < n; i++){
    b[i] = new BigInteger(in.next());
}

Upvotes: 0

GhostCat
GhostCat

Reputation: 140457

Here:

b[i] = new BigInteger(String s(i));

should be:

b[i] = new BigInteger(s[i]);

In other words: you got half of your syntax correct; but then seem to forget how to read an already defined array slot:

  • you use [index] square brackets ( "( )" are only used for method invocations)
  • No need to specify that "String" type within that expression

Upvotes: 1

Related Questions