why does the Integer.paseInt() algorithm calculate negative result finally in sun jdk

algorithm, java, java-6

Solution

The code has a comment: "Accumulating negatively avoids surprises near MAX_VALUE"

As the number is parsed, the code adds the digits to the accumulator variable `result`.

Now the author wanted to write the code to build up the number in the accumulator only once for both positive and negative numbers.

Then when it is done, it adds the sign to it; if there was a minus character in front of the number, the result will be made negative, otherwise positive.

The problem is that the number range for integers is not symmetrical for positive and negative numbers. The smallest negative number that fits into an `int` is -2147483648 but the largest positive number if 2147483647.

If the number in the `result` local variable was kept positive, it wouldn't be possible to parse the negative number -2147483648.

That's why the code keeps it negative until the end - because the range of negative numbers is large enough to hold all positive numbers, while the range of positive numbers is one number too small to hold all negative numbers.

Problem

In jdk source,I have some questions about the Integer's parseInt(String str,int radix) algorithm.let's see the code source below. ``` multmin = limit / radix; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE digit = Character.digit(s.charAt(i++),radix); if (digit < 0) { throw NumberFormatException.forInputString(s); } if (result < multmin) { throw NumberFormatException.forInputString(s); } result *= radix; if (result < limit + digit) { throw NumberFormatException.forInputString(s); } result -= digit; } ``` why it is result -= digit rather than result +=digit? I am confused.

Original source