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
source to share
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)
source to share
Instead of BigInteger :
BigInteger i = new BigInteger("65568768");
BigInteger j = new BigInteger("2106140544");
System.out.println((i.longValueExact() + j.longValueExact()));
Output
2171709312
source to share