# Input: "2147483648" Output: 0 Expected: 2147483647

• I don't think the official answer is correct. Below is the test case and my solution. Thanks.
Input:
"2147483648"
Output:
0
Expected:
2147483647

``````public class Solution {
public int myAtoi(String str) {
if (str == null || str.isEmpty()) return 0;
boolean positive = true;
int i = 0;
long rt = 0;
while (str.charAt(i) == ' ') i++;
if (str.charAt(i) == '-') {
positive = false;
i++;
} else if (str.charAt(i) == '+') i++;

for (; i < str.length(); i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
rt = rt * 10 + str.charAt(i) - '0';
if (positive && rt > Integer.MAX_VALUE || !positive && -rt < Integer.MIN_VALUE) return 0;
} else {
return (int) (positive ? rt : -rt);
}
}
return (int) (positive ? rt : -rt);
}
}``````

• I sort of concur.
The problem statement is vague on purpose, so there's lots of gray areas.
However, the specification of atoi I've used as reference reads:

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence
exists because either str is empty or it contains only whitespace characters, no conversion is performed and zero is returned.

So I was returning 0 when the converted value (2147483648) was overflowing.
Then, I also noticed, in the same spec, the "Return Value" section:

On success, the function returns the converted integral number as an int value.
If the converted value would be out of the range of representable values by an int, it causes undefined behavior.

So, really we're in a case left undefined by the spec. From that test, it looks to me that we should return the int_max value when overflowing, and I'm assuming int_min value when underflowing.

• Thanks. Your explain is reasonable. Yes, it's closest to the true value in the edge cases. While returning INT_MAX or INT_MIN, that means it is reaching the edge. So the return value is not sure.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.