如何获得BigInteger中的第n个数字?

时间:2019-08-10 12:36:30

标签: java biginteger

我正在研究一些BigInteger问题,每个数字的大小为2 ^ 100。我需要该数字的第n个数字。我该怎么做?

使用toString()我将BigInteger转换为String,然后获得了该数字 但是,字符串的大小最多只能达到Int的最大值吗?

int get(BigInteger b,BigInteger n)
{
  return Character.getNumericValue(b.toString().charAt(n.intValue()));
}

因此,仅当BigInteger小于Int max值时,此代码才有效。 但是在我的情况下,经过某些迭代后,可能是我的BigInteger交叉限制的机会,因此如何在该BigInteger中获得第n个BigInteger数字?

1 个答案:

答案 0 :(得分:6)

您可以尝试使用BigInteger#toString并使用charAt(int i)...我为您编写了一个Test:

@Test
void testBigInt(){
    BigInteger bi = new BigInteger("123456789012345678901234567890");
    System.out.println(bi.toString().charAt(25));
}

跑步时,我得到一个“ 6”的字样……看起来很正确

当您在“ charAt()”中使用的位置整数太大(大于maxIntValue)时,您将需要对原始BigInteger取模并进行除法

您可以“截断”第一个和最后一个数字,而只查看您感兴趣的范围

    @Test
public void testIt() {
    BigInteger bi = new BigInteger("1234567890");
    BigInteger resDiv = bi.divide(new BigInteger("100000"));
    System.out.println(resDiv.toString());
    BigInteger resMod = resDiv.mod(new BigInteger("1234"));

    System.out.println(resMod.toString());

}
相关问题