Freigeben über


Max Int Min Int - a Common Coding Mistake and a Sample Microsoft Interview Question

Write the function atoi, a string to integer converter.
Write the function itoa, an integer to string converter.

These are problems given to a lot of entry level interview candidates at Microsoft.  I want to talk about just one aspect of this type of problem that most people do not get(maybe even the interviewer)!  This subtle yet valid trap actually can happen a lot in real life coding situations.

Depending on how you designed your answer, you might eventually come down to a path where the number you want to eventually return is a negative number, but you are keeping it as a positive integer until the last second, when you either multiply it by -1 or add the positive number to the end of a string with '-' char.  There is a subtle trap here.  What if the number passed in is the maximum negative integer, or rephrased, the minimum int possible.  I'll end the suspense right now, the absolute value of max int is smaller than the absolute value of min int.  Ie Take a signed byte.  The max signed byte value would be 2^7-1, but the min int value would be -2^7.  If you think about it, with 8 binary digits, you can fit 2^8 distinct values in.  So if the positive side contains 2^7-1 numbers, and one more for the 0, the negative side must contain 2^7 numbers.  To illustrate:

00000000 - 0
01111111 - max signed byte, 2^7-1
11111111 - 2's complement -> 00000001
10000000 - 2's complement -> 10000000

 In summary, max int != - min int

 Update: Read an excellent XKCD episode that contained the same concept at https://xkcd.com/571/.