since it is integer, don't worry about decimal point or e, and be careful of the first digit is + or -. Remember to result = 10 * result + cur Number.
public class Solution {
public int atoi(String str) {
if(str == null || str.length() == 0){
return 0;
}
str = str.trim();
int digits = 0;
if(str.charAt(0) == '+' || str.charAt(0) == '-'){
digits = str.length() - 1;
}else{
digits = str.length();
}
long result = 0;
int loopDigit = str.length() - digits;
while(loopDigit < str.length()){
if(str.charAt(loopDigit) < 48 || str.charAt(loopDigit) > 57) {
break;
}
result = 10 * result + (str.charAt(loopDigit) - 48);
loopDigit++;
}
if(str.charAt(0) == '-'){
result = result * (-1);
}
if(result > Integer.MAX_VALUE){
return Integer.MAX_VALUE;
}
if(result < Integer.MIN_VALUE){
return Integer.MIN_VALUE;
}
return (int)result;
}
}
没有评论:
发表评论