LeetCode8. 请你来实现一个myAtoi(string s)函数,使其能将字符串转换成一个32位有符号整数(类似C/C++中的atoi函数)。
我们要先考虑一些极端的情况,输入的字符串中有一堆没用的空格,需要跳过这些空格,如果输入的字符串中全是空格的话,就要加一个判断语句,如果当前索引等于字符串长度,返回。
如果字符串中的数字是带符号的,也要先一步进行处理。
在最后将每一位转换成数字的时候要带着sign乘。
对于输入的 -123
,代码会按照以下步骤进行处理:
firstChar
为'-'
,将sign
设为-1
,并将索引index
增加 1。charArray[index]
为'1'
,将其转换为整数1
并乘以sign
的值-1
,得到-1
,累加到res
中。- 继续检查下一个字符
'2'
,将其转换为整数2
并乘以-1
,得到-2
,累加到res
中。 - 继续检查下一个字符
'3'
,将其转换为整数3
并乘以-1
,得到-3
,累加到res
中。
最终,res
的值会是 -123
。
因此,在乘法操作中,需要将符号位 sign
乘进去,以处理负数的情况。
public static int myAtoi(String str) {
int len = str.length();
char[] charArray = str.toCharArray();
// 1. 去除前导空格
int index = 0;
while (index < len && charArray[index] == ' ') {
index++;
}
// 2. 如果已经遍历完成(针对极端用例" ")
if (index == len) {
return 0;
}
// 3. 如果出现符号字符,仅第 1 个有效,并记录正负
int sigh = 1;
char firstChar = charArray[index];
if (firstChar == '+') {
index++;
} else if (firstChar == '-') {
index++;
sign = -1;
}
// 4. 将后续出现的数字字符进行转换
// 不能使用 long 类型,这是题目说的
int res = 0;
while (index < len) {
char currChar = charArray[index];
// 4.1 先判断不合法的情况
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;
}
// 合法的情况下,才考虑转换,每一步都把符号位乘进去
// 想想这里为什么要带着sign乘
res = res * 10 + sign * (currChar - '0');
index++;
}
return res;
}