Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the result modulo INT_MAX?

Tags:

java

string

If I try to apply: Integer.valueOf(String.valueOf(Integer.MAX_VALUE) + "9");
I get a NumberFormatException.

But I need to get the remainder modulo Integer.MAX_VALUE from the String representation.

How can I achieve that?

UPD: Integer.valueOf(String.valueOf(Integer.MAX_VALUE) + "9"); is just an example. The string can potentially have the value even more than max of Long.

like image 593
user3663882 Avatar asked Feb 02 '26 16:02

user3663882


2 Answers

You are looking for BigInteger. This allows math using very large numbers.

The following will allow you to do modulo with very large numbers:

BigInteger number = new BigInteger(myValueAsString);
BigInteger intMax = BigInteger.valueOf(Integer.MAX_VALUE);
BigInteger remainder = number.remainder(intMax);
like image 154
Thirler Avatar answered Feb 04 '26 06:02

Thirler


To hold large number of input you can try BigInteger class. create one object that will hold your String input and modulo it with second BigInteger class object that will hold MAX_VALUE of integer.

You can write code as :

        BigInteger bigInteger = new BigInteger(str);
        bigInteger  = bigInteger.remainder(new BigInteger(String.valueOf(Integer.MAX_VALUE)));
        System.out.println(bigInteger);
like image 30
Prashant Avatar answered Feb 04 '26 04:02

Prashant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!