1, 考虑溢出 -》用long。 If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
2,考虑+、-
3,考虑最左边的空白符
4,考虑最右边additional characters,所以要有个else break
public class Solution {
public int atoi(String str) {
//consider overflow
long res = 0;
boolean negative = false;
if (str.length() == 0) return 0;
int i = 0;
int len = str.length();
//consider the whitespace at the begining of the String
while (i < len && str.charAt(i) == ' ') {
i++;
}
if (i == len) {
return 0;
}
//consider +/-
if (str.charAt(i) == '+' || str.charAt(i) == '-') {
if (str.charAt(i) == '-') {
negative = true;
}
i++;
}
for (; i < str.length(); i++) {
int temp = str.charAt(i) - '0';
if (temp >= 0 && temp <= 9) {
res = res *10 + temp;
if (!negative && res >= Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (negative && res >= (long)Integer.MAX_VALUE + 1) {
return Integer.MIN_VALUE;
}
} else {
//consider additional characters
break;
}
}
if (negative) {
res = -res;
}
return (int)res;
}
}