I am tring to implement C/C++ atoi function in Java, below is the code snippet
for (int j = 0; j < s.length(); j++) {
int digit = Character.digit(s.charAt(j), 10);
if (sum < limit/10) {
if (neg) return Integer.MIN_VALUE;
return Integer.MAX_VALUE;
}
sum *= 10;
if (sum < limit + digit) {
if (neg) return Integer.MIN_VALUE;
return Integer.MAX_VALUE;
}
sum -= digit;
}
For line "if (sum < limit + digit) {", which is correct, however, if I use "sum - digit < limit", it will get wrong result, e.g. input "-2147483649", wrong result 2147483647, should be -2147483648.
I figured this out, cuz sum - digit might be overflow, so this come to another question:
int sum = Integer.MAX_VALUE;
System.out.println(sum < Integer.MAX_VALUE + 1);
Why this prints false? What is the behind logic?
Integer.MAX_VALUE + 1produce?