How do I convert a String to a BigInteger?

前端 未结 6 1391
自闭症患者
自闭症患者 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:46

    For a loop where you want to convert an array of strings to an array of bigIntegers do this:

    String[] unsorted = new String[n]; //array of Strings
    BigInteger[] series = new BigInteger[n]; //array of BigIntegers
    
    for(int i=0; i<n; i++){
        series[i] = new BigInteger(unsorted[i]); //convert String to bigInteger
    }
    
    0 讨论(0)
  • 2020-11-30 08:47

    Instead of using valueOf(long) and parse(), you can directly use the BigInteger constructor that takes a string argument:

    BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");
    

    That should give you the desired value.

    0 讨论(0)
  • 2020-11-30 08:49

    Using the constructor

    BigInteger(String val)

    Translates the decimal String representation of a BigInteger into a BigInteger.

    Javadoc

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-11-30 09:05

    BigInteger has a constructor where you can pass string as an argument.

    try below,

    private void sum(String newNumber) {
        // BigInteger is immutable, reassign the variable:
        this.sum = this.sum.add(new BigInteger(newNumber));
    }
    
    0 讨论(0)
  • 2020-11-30 09:06

    According to the documentation:

    BigInteger(String val)

    Translates the decimal String representation of a BigInteger into a BigInteger.

    It means that you can use a String to initialize a BigInteger object, as shown in the following snippet:

    sum = sum.add(new BigInteger(newNumber));
    
    0 讨论(0)
提交回复
热议问题