JavaApprentice
JavaApprentice

Reputation: 41

Split BigInteger into digits and put them in an array

I want split the following biginteger into digits and put it in an array.

BigInteger = 123456789123456789123456789123456789
array[]={1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,}

How can I do this?Thank you.I searched it but couldn't find a better answer.

Upvotes: 4

Views: 3743

Answers (2)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

Just do toString and turn each character to int and add to array of ints

String biStr = bi.toString();
int[] ints = new int[biStr.length()];
for(int i=0; i<biStr.length(); i++) {
    ints[i] = Integer.parseInt(String.valueOf(biStr.charAt(i)))
}

Upvotes: 1

Vikdor
Vikdor

Reputation: 24124

Could do it as follows:

BigInteger value = new BigInteger("123456789123456789123456789123456789");
List<Integer> list = new ArrayList<Integer>();
BigInteger ten = new BigInteger("10");
while (!value.equals(BigInteger.ZERO))
{
    list.add(0, value.mod(ten).intValue());
    value = value.divide(ten);
}

Upvotes: 5

Related Questions