Why is absolute of Integer.MIN_VALUE equivalent to Integer.MIN_VALUE

前端 未结 6 1371
感动是毒
感动是毒 2020-12-31 12:12

In java when I say Integer i = Math.abs(Integer.MIN_VALUE). I get the same value as the answer,which means i contains Integer.MIN_VALUE

6条回答
  •  感动是毒
    2020-12-31 12:52

    Read this in Effective Java by Joshua Bloch.

    I found the answer for this question and here is the explanation: Computers work with binary arithmentic, the logic of Math.abs in java or the absolute function in any language is like below:

    if(num >= 0)
        return num;
    else
        return (2's complement of the num);
    

    Note : How to find 2's complement

    For a given number, we find it's 1's complement first and then add 1 to it. For e.g. Consider our number to be 10101 1's complement= 01010 2's complement= 01011 (added 1 to the 1`s complement)

    Now, for the sake of making it easy and clear, let us say that our Integer(signed) size is 3 bit, then here is the possible list of numbers which can be produced using the four bits:

    000 --> 0 (0)
    001 --> 1 (1)
    010 --> 2 (2)
    011 --> 3 (3) 
    100 --> 4 (-4)
    101 --> 5 (-3)
    110 --> 6 (-2)
    111 --> 7 (-1)
    

    Now that this is signed, it means half of the numbers are negative and the other half are positive(The negative numbers are the ones with the first bit 1). Let us start from 000 and try to find its negative number, it would be the two's complement of 000.

    2's complement of `000` = 1 + `111` = `000`
    2's complement of `001` = 1 + `110` = `111`
    2's complement of `010` = 1 + `101` = `110`
    2's complement of `011` = 1 + `100` = `101`
    2's complement of `100` = 1 + `011` = `100`
    2's complement of `101` = 1 + `010` = `011`
    2's complement of `110` = 1 + `001` = `010`  
    2's complement of `111` = 1 + `000` = `001`
    

    From the above demonstration, we find that 2's complement of 111(-1) is 001(1), similarly 2's complement of 110(-2) is 010(2), 2's complement of 101(-3) is 011(3) and 2's complement of 100(-4) is 100(-4) and as we can see that -4 is the smallest negative number possible using 3 bits.

    This is the reason why absolute of Integer.MIN_VALUE is Integer.MIN_VALUE.

提交回复
热议问题