When I submit my code to Leetcode, it reported runtime error as:
Runtime Error Message: Line 8: java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
I tested that case in my local, it works fine. I thought it maybe causeed by the platform and compiler are different. I then tried to test it on Leetcode Playground. It also worked very well. The Leetcode problem is:https://leetcode.com/problems/string-to-integer-atoi/ I would be very appreciated if anyone could let me know what's wrong with my code.
class Solution{
public int myAtoi(String str) {
if (str == null || str.length() == 0) return 0;
char chs[] = str.toCharArray();
long base = 0;
int i = 0, sign = 1;
while (chs[i] == ' ' && i < str.length()){
i++;
}
if(i == str.length()){
return 0;
}
if (chs[i] == '-') {
i++;
sign = -1;
} else if (chs[i] == '+') {
i++;
}
while (i < str.length() && (chs[i] >= '0' && chs[i] <= '9')) {
base = base * 10 + (chs[i] - '0');
if (sign * base > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if (sign * base < Integer.MIN_VALUE) return Integer.MIN_VALUE;
i++;
}
return (int)(sign * base);
}
}