1

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));
}
1
  • You don't really need to populate an array of Strings and convert it later to an array of BigInteger. You can do it with just one for loop. BigInteger[] b = new BigInteger[n]; for(int i=0; i < n; i++){ b[i] = new BigInteger(in.next()); } Commented Feb 21, 2017 at 11:33

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.