你如何将一个长整数字符串转换为BigInteger?

0 java string biginteger

我被困在代码的这一部分上.我有一个存储在输入中的字符串.

String input = ("831346848 2162638190 2014846560 1070589609 326439737");
Run Code Online (Sandbox Code Playgroud)

该字符串包含长整数.我试图通过将每个长整数转换为BigInteger来实现它们.例如,从字符串中,我需要这样做:

 BigInteger bi1= new BigInteger("831346848");
Run Code Online (Sandbox Code Playgroud)

等等.输入字符串非常长,所以我需要把它放在某种循环中.在我暂时将它存储到bi1后,我需要执行b1.modPow(exp,mod).然后对字符串中的每个长整数重复这些步骤.那部分我理解,但我困惑的部分是如何将输入字符串放在循环中,以便将它存储在bi1中.

长整数由空格分隔,字符串中的每个长整数长度不同.

实现这个的最佳方法是什么?

sid*_*ate 6

Java-8方式

List<BigInteger> bigIntegers = Stream.of(input.split(" "))
    .map(BigInteger::new)
    .map(bi -> bi.modPow(exp, bi))
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)


Rak*_* KR 5

通过分割字符串space,并将其存储在ListBigInteger

String input = "831346848 2162638190 2014846560 1070589609 326439737";

List<BigInteger> bigIntegerList = new ArrayList<BigInteger>();

for(String value : input.split("\\s")){
     bigIntegerList.add(new BigInteger(value));
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的快速反应,这非常有效!不知道为什么我没想到这个! (2认同)