Bad reputation on leetcode, but essentially a good one from my perspective.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public int myAtoi(String str) {
if (str.length() == 0) return 0;
int i = 0, sign = 1, total = 0;
while (i < str.length() && str.charAt(i) == ' ') i++;
if (i == str.length()) return 0;
if (str.charAt(i) == '+' || str.charAt(i) == '-') {
sign = str.charAt(i) == '+' ? 1 : -1;
i++;
}
while (i < str.length()) {
int digit = str.charAt(i) - '0';
if (digit > 9 || digit < 0) break;
if (total > Integer.MAX_VALUE / 10 || total == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
total = 10 * total + digit;
i++;
}
return sign * total;
}
}

while (i < str.length() && str.charAt(i) == ' '): i<str.length() has to be the 1st condition;

if (total > Integer.MAX_VALUE ...: only Integer.MAX_VALUE because sign is decided in the front.