🔥题目
写一个函数 StrToInt,实现把字符串转换成整数这个功能。
首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。
当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。
该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。
说明1:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。在任何情况下,若函数不能进行有效的转换时,请返回 0。
说明2:假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−2^31, 2^31 − 1]。如果数值超过这个范围,请返回 Integer.MAX_VALUE 或 Integer.MIN_VALUE 。
我建议你不要读上面的题目,直接看下面提供的输入输出样例:
输入:“2233”
输出:2233
输入:" -42"
输出:-42
输入:“4193 with words”
输出:4193
输入:“words and 987”
输出:0
输入:"-91283472332"
输出:-2147483648
☘️解析
非常朴素的单指针扫描,但需要考虑诸多种情况。
无需分析,直接读代码即可。
🧊代码
class Solution {
public int strToInt(String str) {
char[] chars = str.toCharArray();
int len = chars.length;
int index = 0;
while (index < len && chars[index] == ' ') {
// 去掉前导空格
index++;
}
if (index == len) {
// 去掉空格直接到达末尾的情况
return 0;
}
boolean sign = true;
if (Character.isDigit(chars[index])) {
// 遇到数字
} else if (chars[index] == '+') {
// 遇到正号
sign = true;
index++;
} else if (chars[index] == '-') {
// 遇到负号
sign = false;
index++;
} else {
// 其他符号都不合法
return 0;
}
int res = 0;
while (index < len && Character.isDigit(chars[index])) {
int digit = chars[index] - '0';
// 本来应该是 res = res * 10 + digit > Integer.MAX_VALUE
// 但是 *10 和 +digit 都有可能越界,都移到右边变成除法就可以了
if (res > (Integer.MAX_VALUE - digit) / 10) {
return sign ? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
res = res * 10 + digit;
index++;
}
return sign ? res : -res;
}
}
🌸补充
这是一道无聊且麻烦的题目。但依旧有一些可取之处:
1)用一个boolean变量记录符号,之后看作正数处理;
2)对溢出进行判断时,使用了移项的小技巧,避免了溢出的真正发生。