Symphonious

Living in a state of accord.

  • Milo says:

    That would be Integer.MIN_VALUE :)

    September 14, 2006 at 10:46 am
  • Milo says:

    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 14, 2006 at 10:51 am
  • Adrian Sutton says:

    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 14, 2006 at 11:17 am
  • Milo says:

    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 14, 2006 at 4:59 pm
  • Milo says:

    Gah, hit submit while checking that post. min is -4 not -3.

    September 14, 2006 at 5:02 pm

Your email address will not be published. Required fields are marked *

*