A data type that never makes a sum negative

I am dynamically calculating the byte size based on the existing size and the incoming size. But when values ​​grow outside of the result it becomes negative

int i = 65568768;
int j = 2106140544;
System.out.println(i+j);

      

Is there a way that I can withhold the amount without losing its sign. I am calculating an array of size by .length

+3


source to share


3 answers


int is not large enough. Try with a long description of the suffix L

.

For example:

long v = 65568768L + 2106140544L;
System.out.println(v);

      

If you write:



long v = 65568768 + 2106140544;

      

you will have the same problem as if the type was not specified, the numbers without the floating part by default int

.

65568768

+ 2106140544

= 2171709312


and 2171709312

> 2147483647

(Integer.MAX_VALUE)

+1


source


Instead of BigInteger :

BigInteger i = new BigInteger("65568768");
BigInteger j = new BigInteger("2106140544");
System.out.println((i.longValueExact() + j.longValueExact()));

      



Output

2171709312

      

+1


source


BigInteger worked for me:

import java.math.BigInteger;

BigInteger i = new BigInteger("65568768");
BigInteger j = new BigInteger("2106140544");
System.out.println(i.add(j));

      

Output:

2171709312

The javadoc is here .

+1


source







All Articles