How do I convert a String to a BigInteger?

前端 未结 6 1402
自闭症患者
自闭症患者 2020-11-30 08:09

I\'m trying to read some really big numbers from standard input and add them together.

However, to add to BigInteger, I need to use BigInteger.valueOf(long);

6条回答
  •  自闭症患者
    2020-11-30 08:49

    If you may want to convert plaintext (not just numbers) to a BigInteger you will run into an exception, if you just try to: new BigInteger("not a Number")

    In this case you could do it like this way:

    public  BigInteger stringToBigInteger(String string){
        byte[] asciiCharacters = string.getBytes(StandardCharsets.US_ASCII);
        StringBuilder asciiString = new StringBuilder();
        for(byte asciiCharacter:asciiCharacters){
            asciiString.append(Byte.toString(asciiCharacter));
        }
        BigInteger bigInteger = new BigInteger(asciiString.toString());
        return bigInteger;
    }
    

提交回复
热议问题