The following also applies to others MIN_VALUE
and MAX_VALUE
, but now focus only on Integer
. I know that in Java, integers are 32-bit, with Integer.MAX_VALUE = 2147483647
(2 31 -1) and Integer.MIN_VALUE = -2147483648
(-2 31 ). When calculating with these values, when you go beyond your borders, the number wraps around / overflows. Therefore, when you do something like Integer.MAX_VALUE + 1
, the result will be the same as Integer.MIN_VALUE
.
Here are some basic arithmetic calculations with MIN_VALUE
and MAX_VALUE
:
Integer.MAX_VALUE: 2147483647
Integer.MAX_VALUE + 1: -2147483648
Integer.MAX_VALUE - 1: 2147483646
Integer.MAX_VALUE * 2: -2
Integer.MAX_VALUE * 3: 2147483645
Integer.MAX_VALUE * 4: -4
Integer.MAX_VALUE * 5: 2147483643
Integer.MAX_VALUE / Integer.MAX_VALUE: 1
Integer.MAX_VALUE * Integer.MAX_VALUE: 1
Integer.MAX_VALUE / Integer.MIN_VALUE: 0
Integer.MAX_VALUE * Integer.MIN_VALUE: -2147483648
Integer.MAX_VALUE - Integer.MIN_VALUE: -1
Integer.MAX_VALUE + Integer.MIN_VALUE: -1
-Integer.MAX_VALUE: -2147483647
-Integer.MAX_VALUE - 1: -2147483648
-Integer.MAX_VALUE + 1: -2147483646
Integer.MIN_VALUE: -2147483648
Integer.MIN_VALUE + 1: -2147483647
Integer.MIN_VALUE - 1: 2147483647
Integer.MIN_VALUE * 2: 0
Integer.MIN_VALUE * 3: -2147483648
Integer.MIN_VALUE * 4: 0
Integer.MIN_VALUE * 5: -2147483648
Integer.MIN_VALUE / Integer.MAX_VALUE: -1
Integer.MIN_VALUE / Integer.MIN_VALUE: 1
Integer.MIN_VALUE * Integer.MIN_VALUE: 0
Integer.MIN_VALUE - Integer.MAX_VALUE: 1
-Integer.MIN_VALUE: -2147483648
-Integer.MIN_VALUE - 1: 2147483647
-Integer.MIN_VALUE + 1: -2147483647
Or more generally (iff MIN == -MAX-1
):
MAX: MAX
MAX + 1: MIN
MAX - 1: MAX - 1
MAX * 2: -2
MAX * 3: MAX - 2
MAX * 4: -4
MAX * 5: MAX - 4
MAX / MAX: 1
MAX * MAX: 1
MAX / MIN: 0
MAX * MIN: MIN
MAX - MIN: -1
MAX + MIN: -1
-MAX: MIN + 1
-MAX - 1: MIN
-MAX + 1 MIN + 2
MIN: MIN
MIN + 1: MIN + 1
MIN - 1: MAX
MIN * 2: 0
MIN * 3: MIN
MIN * 4: 0
MIN * 5: MIN
MIN / MAX: -1
MIN / MIN: 1
MIN * MIN: 0
MIN - MAX: 1
-MIN: MIN
-MIN - 1: MAX
-MIN + 1: MIN + 1
My question is: how can I manually reproduce all the basic arithmetic operations ( +-*/
) manually?
, , modulo. :
long reproduceMinMaxFromLongToInt(long n){
if(n > 2147483647L){
return n % 2147483648L;
}
if(n < -2147483648L){
return n % -2147483648L;
}
return n;
}
, . ( , TIO , - .) :
Calculation: Should be But is instead
MAX_VALUE + 1: -2147483648 0
MAX_VALUE * 2: -2 2147483646
MAX_VALUE * 4: -4 2147483644
MAX_VALUE * MIN_VALUE: -2147483648 0
MAX_VALUE - MIN_VALUE: -1 2147483647
MIN_VALUE - 1: 2147483647 -1
MIN_VALUE * 3: -2147483648 0
MIN_VALUE * 5: -2147483648 0
-MIN_VALUE - 1: 2147483647 2147483647
.
reproduceMinMaxFromLongToInt
, ( , Power, Modulo, Root ..)?
, , , , , ( )?
EDIT: . Integer
. , int
. , min
/max
, , min=-100; max=99
.