String to Integer (atoi)
convert string to integer.
pay attention to the following problems:
the number might be positive/negative.
there might be spaces on the first/last
there might be other characters in the given string, and if the first char is a non numerical char, then we return 0
if it is overflow the integer range, please return the closest boundary.
class Solution {
public int myAtoi(String str) {
str = str.trim();
if(str==null||str.length()==0) return 0;
//char firstChar = str.charAt(0);
int start = 0;//this indicates the first numerical char index of this string
int sign = 1;
long res = 0;//potentiially overflow preprocess
//initial start and sign
if(str.charAt(0) == '+'){
start = 1;
} else if(str.charAt(0) == '-'){
start = 1;
sign = -1;
}
//iterate from start to the end
for(int i = start;i<str.length();i++) {
if(!Character.isDigit(str.charAt(i))){ //if find something that is not numerical, then we just break this
break;
}
//classic string to integer
res = res * 10 + str.charAt(i) - '0';
//check if overflow or not
if(sign == 1 && res > Integer.MAX_VALUE) return Integer.MAX_VALUE;
if(sign == -1 && res > Integer.MAX_VALUE) return Integer.MIN_VALUE;//至于这边为什么不能res>Integer.MAX_VALUE+1,因为Integer.MAX_VALUE+1了之后就变成Integer.MIN_VALUE了而如果res>Integer.MAX_VALUE的话 res>=abs(Integer.min)都会返回MIN_VALUE了
}
return (int)res * sign; //return int
}
}
the code above have the clearest mind.

浙公网安备 33010602011771号