Question

If you run the statement:

System .out.println( (Integer.MIN_VALUE)-(Integer .MAX_VALUE ));

In java it returns 1 as the answer. Is this because Java just considers those values as 32bit integers without considering their sign?

Integer.MIN_VALUE = 10000000000000000000000000000000
Integer.MAX_VALUE = 1111111111111111111111111111111

I get that why -MIN.VALUE == MIN_VALUE returns true. And how MAX_VALUE+1 causes the Integer overflow and we get the result. But I cannot clearly wrap my head around how subtraction is working.

Était-ce utile?

La solution

Java will overflow and underflow int values.

max_int = 2147483647   (01111111111111111...1)
min_int = -2147483648  (10000000000000000...0) //first bit is -2^31

under flow:

-2147483648 - 1 =  2147483647

so....

 min_int- max_int = -2147483648 - 2147483647 
                  = -2147483648 -(1 + 2147483646)
                  = (-2147483648 - 1) - 2147483646
                  = 2147483647 - 2147483646 
                  = 1;

Autres conseils

Easy way to wrap your head around it: we have an even number of bits to store a number in. We define 0 as the "middle" point of a range of even numbers. There has to be a difference of 1 either on the positive or negative side of 0 because the middle point is an odd amount in an even set of posible numbers.

Imagine having 8 bits integers. Where is the "most middle" point of that? Either the forth or fifth bit:

00010000 //3 bits on the "positive side", 4 bits on the "negative side" 
00001000 //4bits positive, 3 bits negative
Licencié sous: CC-BY-SA avec attribution
scroll top