把字符串转换成整数
//leetcode8
public class Solution {
public int myAtoi(String str) {
int index = 0;
int sign = 1;
int total = 0;
//1. Empty string
if(str.length() == 0) {
return 0;
}
//2. Remove Spaces 去掉string开头处的空格
while (str.charAt(index) == ' ' && index < str.length())
index++;
//3. Handle signs 如果string开头是+,最后结果为正
if(str.charAt(index) == '+' || str.charAt(index) == '-') {
sign = str.charAt(index) == '+' ? 1 : -1;
index++; //要记住判断完后,index加1
}
//4. Convert number and avoid overflow
while(index < str.length()) {
int digit = str.charAt(index) - '0'; //记住要减'0',否则str等于111,str.charAt(0)是1,1的ascii码是49
if(digit < 0 || digit > 9)
break;
//check if total will be overflow after 10 times and add digit 判断是不是overflow,如果满足if条件,就会大于2^31-1,是的话就取到 Integer.MAX_VALUE
if(Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE / 10 == total && Integer.MAX_VALUE % 10 < digit)
return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
total = 10 * total + digit;
index ++;
}
return total * sign;
}
}
浙公网安备 33010602011771号