感冒也要坚持刷题,不过看后面我check的不同case就看出脑袋不太清楚了。。。
Question
Implement atoi to convert a string to an integer.
The atoi function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or
if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, the maximum integer value (2147483647) or the minimum integer value (–2147483648) is returned.
*Difficulty: Easy, Frequency: High
Comments
考验各种edge cases,逻辑清楚
*How to check integer is overflow
https://leetcode.com/problems/string-to-integer-atoi/
My Solution
public int myAtoi(String str) {
int num = 0, MAX=2147483647, MIN=-2147483648;
boolean ifPos = true;
boolean shouldStartDigit = false;
for(int i= 0; i < str.length(); i++){
if(str.charAt(i) == '-' || str.charAt(i) == '+'){
if(shouldStartDigit) return ifPos ? num : -1*num;
ifPos = (str.charAt(i) == '-') ? false : true;
shouldStartDigit = true;
}
else if(!Character.isDigit(str.charAt(i)) && (shouldStartDigit || str.charAt(i) != ' ') ) return ifPos ? num : -1*num;
else if(!Character.isDigit(str.charAt(i))) continue;
else{
if(num > 214748364 || (num == 214748364 && (str.charAt(i) == '9' || (ifPos && str.charAt(i)=='8')))) return ifPos ? MAX : MIN;
else if(num == 214748364) return ifPos ? num*10+Integer.parseInt(str.charAt(i)+"") : -10 *num-Integer.parseInt(str.charAt(i)+"");
else num = num * 10 + Integer.parseInt(str.charAt(i)+"");
shouldStartDigit=true;
}
}
return ifPos ? num : -1*num;
}
Standard Solution
private static final int maxDiv10 = Integer.MAX_VALUE / 10;
public int atoi(String str) {
int i = 0, n = str.length();
while (i < n && Character.isWhitespace(str.charAt(i))) i++;
int sign = 1;
if (i < n && str.charAt(i) == '+') {
i++;
} else if (i < n && str.charAt(i) == '-') {
sign = -1;
i++;
}
int num = 0;
while (i < n && Character.isDigit(str.charAt(i))) {
int digit = Character.getNumericValue(str.charAt(i));
if (num > maxDiv10 || num == maxDiv10 && digit >= 8) {
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
num = num * 10 + digit;
i++;
}
return sign * num;
}