Hint:Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes:It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
Thoughts
注意 1. 开头空白 2. 符号 3. 非数字的 4. 溢出.
Code
class Solution {
public int myAtoi(String str) {
int res = 0, sign = 1;
// Empty String
if (str == null || str.length() == 0) {
return res;
}
int i = 0;
// RM white spaces
while (str.charAt(i) == ' ') {
i++;
}
// Handle signs
if (str.charAt(i) == '+' || str.charAt(i) == '-') {
sign = str.charAt(i) == '+' ? 1 : -1;
i++;
}
// Convert number and avoid overflow
for (; i < str.length(); i++) {
int digit = str.charAt(i) - '0';
if (digit >= 0 && digit <= 9) {
if (Integer.MAX_VALUE / 10 < res || Integer.MAX_VALUE / 10 == res && Integer.MAX_VALUE % 10 < digit) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + digit;
//System.out.println(res + ", " + (res - digit) / 10);
} else {
break;
}
}
return res * sign;
}
}