Quick Java Puzzler
While I'm waiting for Eclipse to do an update: What's the one value you can pass to Math.abs(int) and get a negative value from?
Just ran into a bug caused because of it - fortunately it was picked up by the tests even before I checked in.

September 14th, 2006 at 10:46 am
That would be Integer.MIN_VALUE :)
September 14th, 2006 at 10:51 am
Oh, and its not like I figured that one out on my own, was one of the many interesting cases listed in a book I think I’ve mentioned before: Java™ Puzzlers: Traps, Pitfalls, and Corner Cases, by Joshua Bloch, Neal Gafter. If you find this puzzle interesting I highly recommend the book. It’s up on safari - http://search.safaribooksonline.com - you can get a trial account for 2 weeks I think so won’t even cost you anything.
September 14th, 2006 at 11:17 am
Yep, in twos-compliment notation, you can always go one value more negative than you can positive (ie: if you can get to +3, you can get to -4).
September 14th, 2006 at 4:59 pm
And for the nerd in me, it took me ages to understand twos-compliment so i love any chance to explain what’s going on, humour me if you will:
Say we have a number system with only 3 bits using twos-compliment. max number you get is 3, min is -3. the bit pattern for each number is:
000 0
001 1
010 2
011 3
100 -4
101 -3
110 -2
111 -1
two’s complement flips the sign on a number by inverting the bit pattern and then adding one. For example, 2 is 010. flip the bits it becomes 101, add one you get 110, which as the table shows is -2. To show the original problem with an example, -4 is 100. flip the bits and you get 011, add 1 and voila, you get 100.
The other cool (i really am a geek) case is negating 0. 000 flips to 111, we add 1 and we get 1000, but since we only have 3 bits, the leading 1 is lost and we end up with 000. So with twos-complements there are always 2 numbers that when negated will equal themself: 0 and the min.
September 14th, 2006 at 5:02 pm
Gah, hit submit while checking that post. min is -4 not -3.