This question is not very difficult. People may get frustrated by the low AC rate of it. But actually, the tricky part is just to take care of some special cases.
Firstly, check out the aoti page in cplusplus.com, which tells me if "bad" cases were met, return 0; secondly, be careful of cases like "-2147483647" ,"-2147483648", "2147483648", whose absolute value is larger than or equal to Integer.MAX_VALUE, or Integer.MIN_VALUE.
To determine whether result might be larger than or equal to Integer.MAX_VALUE in the loop, I use a long integer to store the temp result, so that it will not get overflowed when 2147483648 is the case.
public class Solution {
public int atoi(String str) {
if(str == null || str.equals(""))return 0;
long tmpRes = 0;
int res = 0;
int numValChar = 0;
boolean isNeg = false;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == ' ' && numValChar == 0){
continue;
}
else{
if(str.charAt(i) == '-' && numValChar == 0){
isNeg = true;
numValChar++;
}
else{
if(str.charAt(i) == '+' && numValChar == 0){
numValChar++;continue;
}
if(str.charAt(i) < '0' || str.charAt(i) > '9'){//invalid characters exist
res = (int)tmpRes;
return (isNeg? -1*res: res);
}
else{
tmpRes=tmpRes*10+(str.charAt(i) - '0');
if(tmpRes > Integer.MAX_VALUE){
return (isNeg? Integer.MIN_VALUE : Integer.MAX_VALUE);
}
numValChar ++;
}
}
}
}
res = (int) tmpRes;
return (isNeg? -1*res: res);
}
}
No comments:
Post a Comment