user1020415
user1020415

Reputation: 33

Split BigInteger, Count Digits?

Any chance you might be able to think of an efficient way to split a BigInteger in half, i.e. if the number is 12345678, it would be split into 1234? I was thinking that I could change it into a string and use substring, but I'm not sure if that would be the fastest way to do it.

Do you also know how to count the number of digits in BigInteger? I know that you can do a bitLength and bitCount, but I think those are in two's complements. I'm trying to keep track of where I split them?

Upvotes: 1

Views: 3126

Answers (3)

Prince John Wesley
Prince John Wesley

Reputation: 63688

    BigInteger bi = new BigInteger("12345678");
    String numStr = bi.toString();
    System.out.println(numStr.substring(0,numStr.length()/2));

Upvotes: 3

pra9ma
pra9ma

Reputation: 388

Converting to String is probably your best bet because it sounds like you're looking for the 'textual' half point and length, which is not something that 'numerical' representations provide.

Upvotes: 1

David Tinker
David Tinker

Reputation: 9634

Some asked how to calculate the number of decimal digits in a binary number here: https://math.stackexchange.com/questions/3987/how-to-calculate-the-number-of-decimal-digits-for-a-binary-number

Seems like its not trivial. So it is very likely that you will have to convert to a String and work from there.

Upvotes: 1

Related Questions