一道基本题,当中的确有很多的考点,都是基本功的考察。
我们当中列了6条。
public class Solution {
public int myAtoi(String str) {
// 1. null or empty string
if (str == null || str.length() == 0) {
return 0;
}
// 2. whitespaces
str = str.trim();
// 3. +/- sign
boolean positive = true;
int i = 0;
if (str.charAt(i) == '+') {
i++;
} else if (str.charAt(i) == '-') {
positive = false;
i++;
}
double temp = 0.0;
for (; i < str.length(); i++) {
// 4. invalid character
if (str.charAt(i) > '9' || str.charAt(i) < '0') {
break;
}
int digit = str.charAt(i) - '0';
// 5. handle min & max
if (positive) {
// 6. calculate real value
temp = temp*10 + digit;
if (temp > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
} else {
temp = temp*10 - digit;
if (temp < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
}
}
int result = (int) temp;
return result;
}
}