如何获得 BigInteger 中的第 n 个数字?
how can I get nth digit in a BigInteger?
我正在研究一些 BigInteger
问题,其中每个数字的大小是 2^100。我需要那个数字的第 n 个数字我该怎么做?
使用 toString()
我将 BigInteger 转换为 String 然后得到那个数字
但是String的大小最多只有Int的最大值?
int get(BigInteger b,BigInteger n)
{
return Character.getNumericValue(b.toString().charAt(n.intValue()));
}
所以这段代码只在 BigInteger 小于 Int 最大值时有效。
但在我的情况下,经过某些迭代后,可能是我的 BigInteger 越过限制的机会,所以如何在那个 BigInteger 中获得第 n 个 BigInteger 数字?
您可以尝试使用 BigInteger#toString 并使用 charAt(int i) ...我为您编写了一个测试:
@Test
void testBigInt(){
BigInteger bi = new BigInteger("123456789012345678901234567890");
System.out.println(bi.toString().charAt(25));
}
当 运行 时,我打印了一个“6”...这似乎是正确的
当您在 "charAt()" 中使用的位置整数太大(大于 maxIntValue)时,您需要对原始 BigInteger
取模并除以
你可以"cut off"第一个和最后一个数字,只看你感兴趣的范围
@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());
}
我正在研究一些 BigInteger
问题,其中每个数字的大小是 2^100。我需要那个数字的第 n 个数字我该怎么做?
使用 toString()
我将 BigInteger 转换为 String 然后得到那个数字
但是String的大小最多只有Int的最大值?
int get(BigInteger b,BigInteger n)
{
return Character.getNumericValue(b.toString().charAt(n.intValue()));
}
所以这段代码只在 BigInteger 小于 Int 最大值时有效。 但在我的情况下,经过某些迭代后,可能是我的 BigInteger 越过限制的机会,所以如何在那个 BigInteger 中获得第 n 个 BigInteger 数字?
您可以尝试使用 BigInteger#toString 并使用 charAt(int i) ...我为您编写了一个测试:
@Test
void testBigInt(){
BigInteger bi = new BigInteger("123456789012345678901234567890");
System.out.println(bi.toString().charAt(25));
}
当 运行 时,我打印了一个“6”...这似乎是正确的
当您在 "charAt()" 中使用的位置整数太大(大于 maxIntValue)时,您需要对原始 BigInteger
取模并除以你可以"cut off"第一个和最后一个数字,只看你感兴趣的范围
@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());
}