[java]
int ret = Math.abs(Integer.MIN_VALUE);
[/java]
In the number system, there are more negative numbers than positive ones. Not all -ve numbers have their positive counterparts (e.g. -3 & +3). Ignoring 0. The minimum possible number in 32 bit number is 10000000000000000000000000000000(31 zeroes, say 1000...0).
Here is how absolute value is calculated.
we take Two's compliment by inverting the whole number (replace 1 with 0 and 0 with 1) and then add 1 to the final value.
Lets do it together:
in 2*32 bit number... 1000...0 is -ve
1) 2s compliment would be:
~100000...0 = 011111...1
2) add 1, would become 01111...11 + 1 = 1000000...0
so its back to the same number Integer.MIN_VALUE
Absolute value of MIN_VALUE is itself.
[java]
Integer.MIN_VALUE = Math.abs(Integer.MIN_VALUE)
[/java]
Note: Math.abs(...) doesn't guarantee to always return positive number. The same is true for "%" operator as it gives remainder but not modulo. Remainder could be negative.
No comments:
Post a Comment