Medium
Zillow OA其实做过:
这道题edge case跟屎一样多,各种千奇百怪的input.
关键点在于:
if (res > Integer.MAX_VALUE / 10){
和if (res == Integer.MAX_VALUE / 10){
这里。
class Solution {
public int myAtoi(String str) {
if (str == null || str.length() == 0){
return 0;
}
str = str.trim();
if (str.length() == 0){
return 0;
}
int res = 0;
int start = 0;
boolean isNegative = false;
if (str.charAt(start) == '-'){
isNegative = true;
start++;
} else if (str.charAt(start) == '+'){
start++;
}
for (int i = start; i < str.length(); i++){
char c = str.charAt(i);
if (c == '+' || c == '-'){
return 0;
}
if (! (c >='0' && c <= '9')){
break;
}
//"-11919730356x"
//-1191973035
if (res > Integer.MAX_VALUE / 10){
if (isNegative){
return Integer.MIN_VALUE;
} else {
return Integer.MAX_VALUE;
}
}
if (res == Integer.MAX_VALUE / 10){
if (isNegative && c > '8'){
return Integer.MIN_VALUE;
} else if (!isNegative && c > '7'){
return Integer.MAX_VALUE;
}
}
res = res*10 + c - '0';
System.out.println(res);
}
if (isNegative){
return - res;
} else {
return res;
}
}
}