LeetCode8. 请你来实现一个myAtoi(String s)函数,使其能将字符串转换成一个32位有符号整数(类似C/C++ 中的atoi函数)。
函数myAtoi(String s) 的算法如下:
注意:
本题中的空白字符只包括空格字符
' '除前导空格或数字后的其余字符串外,请勿忽略任何字符





我们可以从题目给的五个示例中提取出几个要点:
根据这些,我们可以给出如下java代码:
public static int myAtoi(String str) {
int len = str.length();
char[] charArray = str.toCharArray();
//去除前导空格
int index = 0;
while (index < len && charArray[index] == ' ') {
index++;
}
//如果已经遍历完成(针对极端用例" ")
if (index == len) {
return 0;
}
//如果出现符号字符,仅第一个有效,并记录正负
int sign = 1;
char firstChar = charArray[index];
if (firstChar == '+') {
index++;
} else if (firstChar == '-') {
index++;
sign = -1;
}
//将后续出现的数字字符进行转换
//不能使用long类型,这是题目说的
int res = 0;
while (index < len) {
char currChar = charArray[index];
// 先判断不合法的情况
if (currChar > '9' || currChar < '0') {
break;
}
//题目中说只能存储32位大小的有符号整数,下面两个if分别处理整数和负数的情况。
//提前判断乘以10以后是否越界,但res*10可能会越界,所以这里使用Integer.MAX_VALUE/10,这样一定不会越界。
//这是解决溢出问题的经典处理方式。
if (res > Integer.MAX_VALUE / 10 || (res == Integer.MAX_VALUE / 10 && (currChar - '0') > Integer.MAX_VALUE % 10)) {
return Integer.MAX_VALUE;
}
if (res < Integer.MIN_VALUE / 10 || (res == Integer.MIN_VALUE / 10 && (currChar - '0') > -(Integer.MIN_VALUE % 10))) {
return Integer.MIN_VALUE;
}
//合法的情况下,才考虑转换,每一步都把符号位乘进去
//如果不带着符号位乘,当数是负数的时候,每一次识别到的currChar是正数,这样转换的时候不会得到正确值
res = res * 10 + sign * (currChar - '0');
index++;
}
return res;
}